Numpy Flashcards
create a regular array
a=[1,2,3,4]
create a ndarray, or a np array
B=np.array([1,2,3,4,5,6,55,5])
create a numpy array that is 2x5 matrix
a=[[1,2,3,4,5],[6,7,8,9,10]]
A=np.array(a)# create a np array. A is also a 2 by 5 matrix
A
find type
A.dtype
returns a np array starting from 0 to 10, but not including 10. The increment is 2 each time.
np.arange(0,10,2)
array([0, 2, 4, 6, 8])
show the shape of a array
A.shape (2, 5) B=np.array([1, 2, 3, 4, 5]) B.shape (5,)
How do we make B an 5 by 1 matrix?
#reshape function returns to a multi-dim matrix. Bis is 5 element in 1 dimension. Notice the double brackets! B=np.array([1, 2, 3, 4, 5]) print(B.reshape(1,5)) [[1 2 3 4 5]]
reshape to a 3x3 matrix.
only applys to ndarray C =np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) C.reshape(3,3) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
create 4x3 matrix of zeros
np.zeros((4,3)) array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) np.zeros(8) array([0., 0., 0., 0., 0., 0., 0., 0.])
create 2x2 1’s
np.ones((2,2))
array([[1., 1.],
[1., 1.]])
eye stands for Identity and sysmetric. This function retruns to an edentity matrix with specific dimentions.
np.eye(6)
array([[1., 0., 0., 0., 0., 0.], [0., 1., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0.], [0., 0., 0., 1., 0., 0.], [0., 0., 0., 0., 1., 0.], [0., 0., 0., 0., 0., 1.]])
generate another (3 x 3) matrix to be multiplied.
D = np.arange(1,10).reshape(3,3) # no stepsize is specified means stepsize is 1. D array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Please using numpy random to create one 2by4 random uniform array, named A and one 4by2 random uniform array, named B.
Then get the dot product of A and B.
Get the dot product of B and A.
A=np.random.rand(2,4)
B=np.random.rand(4,2)
print(np.dot(A,B))
print(np.dot(B,A))
[[0.41745136 0.36938202]
[0.869284 0.79135864]]
[[0.12728448 0.44244018 0.39016312 0.70958712]
[0.18397938 0.68209005 0.53437116 1.14459566]
[0.12598516 0.45241722 0.37611223 0.74283167]
[0.00561522 0.01666167 0.01919675 0.02332323]]
create float array
A=np.array([[1,2,3,4,5],[6,7,8,9,10]],dtype=np.float64)
A
array([[ 1., 2., 3., 4., 5.],
[ 6., 7., 8., 9., 10.]])
create int array
B=np.array([[1,2,3,4,5],[6,7,8,9,10]],dtype=np.int64)
B
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])
cast array to float
A=np.array([[1,2,3,4,5],[6,7,8,9,10]]) # by defining this, type of A will be int64.
B=A.astype(np.float64)
B
float to int
2
myFloat = -10.8;
print(int(myFloat));