Numpy推荐使用单个括号来访问所有的维度
一次用多个索引
一维
mask = np.ones(7, dtype=bool)
mask[[0, 2, 4]] = False
>>>
[False True False True False True True]
三维
mask = np.ones(36, dtype=bool).reshape((3, 3, 4))
mask[[0, 2]] = False # 将axis=0的索引为0,2的置为false
>>>
[[[False False False False]
[False False False False]
[False False False False]]
[[ True True True True]
[ True True True True]
[ True True True True]]
[[False False False False]
[False False False False]
[False False False False]]]
省略号…
arr = np.array([[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]],
[[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]]])
print(arr.shape)
print(arr[..., :2], arr[..., :2].shape) # (2, 3, 2)维度并未发生变化
print(arr[..., 2], arr[..., 2].shape) # (2, 3)降维了
out>>>
(2, 3, 4)
[[[ 1 2]
[ 5 6]
[ 9 10]]
[[13 14]
[17 18]
[21 22]]] (2, 3, 2)
[[ 3 7 11]
[15 19 23]] (2, 3)
mask操作
- 要求:如果数组a某一行的第0个元素为2,那么将它的第1个元素改为100
做法如下:
a = np.array([
[1,10,1],
[2,20,2],
[3,30,3],
[2,40,4]
])
mask = a[:, 0] == 2 # [False True False True]
a[mask, 1] = 100
[Out]:
[[ 1 10 1]
[ 2 100 2]
[ 3 30 3]
[ 2 100 4]]
- 要求:将数组a 左上角2*2区域 中 小于3或大于4 的元素置0
arr = np.array([[1, 3, 5],
[5, 4, 4],
[2, 4, 3]])
aa = arr[:2, :2]
mask = np.bitwise_or(aa<3,aa>4)
arr[:2, :2][mask] = 0
out >>
[[0 3 5]
[0 4 4]
[2 4 3]]
- 做决策树时碰到的mask操作
要求: 选择索引为 2 的列中值为 0 的所有元素,最后删除索引为 2 的列
features = np.array([[0, 0, 0, 0],
[0, 0, 0, 1],
[0, 1, 0, 1],
[0, 1, 1, 0],
[0, 0, 0, 0],
[1, 0, 0, 0],
[1, 0, 0, 1],
[1, 1, 1, 1],
[1, 0, 1, 2],
[1, 0, 1, 2],
[2, 0, 1, 2],
[2, 0, 1, 1],
[2, 1, 0, 1],
[2, 1, 0, 2],
[2, 0, 0, 0]])
labels = np.array(['no', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 'yes', 'yes', 'yes', 'yes', 'yes']).reshape((-1, 1))
# dataset = np.hstack((features, labels)) # (15, 5)
dataset = np.concatenate((features, labels), axis=1) # (15, 5)
mask = features[:, 2] == 0 # 根据索引为2的列生成mask
subdataset = features[mask] # 将mask为false的行全都去除
subdataset = np.delete(subdataset, 2, axis=1) # 删除索引为2的列