One-dimensional Numpy Flashcards
Creating a numpy array
a = np.array([0,1,2,3,4])
a
Changing an element in an array - same as in list
We can change the value of the array, consider the array c:
# Create numpy array c = np.array([20, 1, 2, 3, 4]) c array([20, 1, 2, 3, 4]) We can change the first element of the array to 100 as follows:
c[0]=100
c
array([100, 1, 2, 3, 4])
Slicing an array
d = c[1:4]
d
array([1, 2, 3])
Select multiple elements
Similarly, we can use a list to select a specific index. The list ‘ select ‘ contains several values:
0,2,3 # Create the index list select = [0,2,3]
We can use the list as an argument in the brackets. The output is the elements corresponding to the particular index:
# Use List to select elements d = c[select] d
array([100, 2, 300])
Number of elements in an array
a.size
Number of dimensions in an array
a.ndim
Mean of an array
a.mean()
Max value
a.max()
Min value
a.min()
Dot product
np.dot(u, v)
7
Add a value to every elements in an array
u + 1
array([2, 3, 4, 0])
Linspace fucntion
np.linspace(-2, 2, num=5)
array([-2., -1., 0., 1., 2.])
Plot vectors
a = np.array([-1, 1])
b = np.array([1, 1])
Plotvec2(a, b)