DS Utilities: Numpy
Numpy
In this Chapter, take the following 25 exercises to learn how to use the basic APIs of
numpy
.
import numpy as np
Z = np.zeros(10)
print(Z)
Z = np.zeros(10)
Z[4] = 1
print(Z)
Z = np.arange(10,50)
print(Z)
Z = np.arange(10)
Z = Z[::-1]
print(Z)
Z = np.arange(10)
Z = Z[::-2]
print(Z)
Z = np.arange(10)
Z = Z[::3]
print(Z)
Z = np.arange(9).reshape(3, 3)
print(Z)
nz = np.nonzero([1,2,0,0,4,0])
print(nz)
Identity matrix: values on positive diagnosis of matrix are 1, and others are 0Also recognized as I_n
Z = np.eye(3)
print(Z)
Z = np.random.random((3,3,3))
print(Z)
Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)
Z = np.random.random(30)
m = Z.mean()
print(m)
Z = np.ones((10,10))
Z[1:-1,1:-1] = 0
print(Z)
Z = np.arange(25).reshape(5, 5)
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
Z = np.diag(np.arange(5))
print(Z)
Chess board Pattern is just like:0 1 0 1 0 1 0 11 0 1 0 1 0 1 00 1 0 1 0 1 0 11 0 1 0 1 0 1 00 1 0 1 0 1 0 11 0 1 0 1 0 1 00 1 0 1 0 1 0 11 0 1 0 1 0 1 0
Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)
# Alternative
Z = np.tile(np.array([[0,1],[1,0]]), (4,4))
print(Z)
print(np.unravel_index(99,(6,7,8)))
Add up two matries A and B, where A and B respectively be:
A = [[1 2 3]
[4 5 6]
[7 8 9]]
B = [[9 8 7]
[6 5 4]
[3 2 1]]
A = np.arange(1, 10).reshape(3, 3)
B = np.arange(9, 0, -1).reshape(3, 3)
print(A + B)
Normalize a matrix(归一化矩阵) is to make every values in the matrix lies on [min, max], as an example: we have an array valued [-1, 1, 3]. After normalization, it becomes [0, 0.5, 1].
Z = np.random.random((5, 5))
Z = (Z - Z.min())/(Z.max() - Z.min())
print(Z)
Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)
Z = np.arange(11)
Z[(3 < Z) & (Z < 8)] *= -1
print(Z)
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(Z1, Z2)
print(np.intersect1d(Z1,Z2))
yesterday = np.datetime64('today') - np.timedelta64(1)
today = np.datetime64('today')
tomorrow = np.datetime64('today') + np.timedelta64(1)
print(yesterday, today, tomorrow)
Z = np.linspace(0,20,6)
print(Z)
Z = np.random.random(10)
Z.sort()
print(Z)
Z = np.random.random(10)
Z[Z.argmax()] = 0
print(Z)
What is the relationship betweenZ.argmax()
andZ.max()
?Z = np.random.random(10)print(Z[Z.argmax()] == Z.max())