import numpy as np
Fancy Index
x = np.array(list('ABCDEFG'))
x # array(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='<U1')
x[1] # 'B'
x[1:3] # array(['B', 'C'], dtype='<U1')
x[1:5] # array(['B', 'C', 'D', 'E'], dtype='<U1')
x[1:5:2] # 等步长 array(['B', 'D'], dtype='<U1')
[x[1], x[2], x[4]] # ['B', 'C', 'E']
ind = [1, 2, 4]
x[ind] # array(['B', 'C', 'E'], dtype='<U1')
ind = np.arange(1, 5).reshape(2, -1)
ind # array([[1, 2],
[3, 4]])
x[ind] # array([['B', 'C'],
['D', 'E']], dtype='<U1')
X = np.arange(16).reshape(4, -1)
X # array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
row = [0, 1, 3]
col = [1, 2, 3]
X[row, col] # array([ 1, 6, 15])
X[1:3, col] # array([[ 5, 6, 7],
[ 9, 10, 11]])
col = [True, True, False, False]
X[1:3, col] # array([[4, 5],
[8, 9]])
比较运算
x = np.arange(10)
x # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x < 5 # array([ True, True, True, True, True, False, False, False, False, False])
x[x<5] # array([0, 1, 2, 3, 4])
x >= 5 # array([False, False, False, False, False, True, True, True, True, True])
x == 5 # array([False, False, False, False, False, True, False, False, False, False])
x != 5 # array([ True, True, True, True, True, False, True, True, True, True])
x - 1 != x // 2 # array([ True, False, False, True, True, True, True, True, True, True])
x + 2 == x // 2 + 3 # array([ True, False, False, True, True, True, True, True, True, True])
x[x + 2 == x // 2 + 3] # array([1, 2])
X < 5 # array([[ True, True, True, True],
[ True, False, False, False],
[False, False, False, False],
[False, False, False, False]])
x = x + 2 # 执行2次
x # array([ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
np.sum(x < 8) # 4
np.count_nonzero(x < 8) # 4
np.any(x < 4) # False
np.any(x <= 4) # True
np.all(x > 4) # False
np.all(x >= 4) # True
np.sum(X % 2 == 0) # 8
np.sum(X % 2 == 0, axis=0) # array([4, 0, 4, 0])
np.sum(X % 2 == 0, axis=1) # array([2, 2, 2, 2])
np.sum((X > 2) & (X < 10)) # 7
np.sum((X == 2) | (X == 10)) # 2
np.sum(~(X == 2)) # 15
X[(X > 2) & (X < 10)] # array([3, 4, 5, 6, 7, 8, 9])
X[:, -1] # array([ 3, 7, 11, 15]),最后1列
X[:, -2] # array([ 2, 6, 10, 14]),倒数第2列
X[:, -1] % 3 == 0 # array([ True, False, False, True])
X[X[:, -1] % 3 == 0] # array([[ 0, 1, 2, 3],
[12, 13, 14, 15]])
X[X[:, -1] % 3 == 0, :] # array([[ 0, 1, 2, 3],
[12, 13, 14, 15]])
X[X[:, -1] % 3 == 0, -1] # array([ 3, 15])
X[X[:, -1] % 3 == 0, 1:3] # array([[ 1, 2],
[13, 14]])
注:代码来自《Python全栈工程师特训班》课程