索引用中括号,数组对象加[]
没有出现逗号时,为行索引
import numpy as np
x = np.arange(12).reshape(4,3)
print(x)
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
x[0]
[0 1 2]
x[1]
[3 4 5]
x[-1]
[ 9 10 11]
当出现:时,返回的是一个二维数组
x[0:1]
[[0 1 2]]
x[0:2]
[[0 1 2]
[3 4 5]]
x[:2] #同上
[[0 1 2]
[3 4 5]]
x[0:-1] #表示从第一行到倒数第二行的索引
[[0 1 2]
[3 4 5]
[6 7 8]]
x[:-1] 同上
[[0 1 2]
[3 4 5]
[6 7 8]]
列索引,逗号前为行索引,逗号后为列索引
x = np.arange(12).reshape(4,3)
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
x[:,2]
[ 2 5 8 11]
x[:1,2]
[2]
x[:1,0:2]
[[0 1]]
使用np.ix_在对应的维度上使用布尔索引,但此时不能使用slice切片
import numpy as np
a = np.arange(1,10).reshape(3,3)
print(a)
b = a[np.ix_([True,False,True],[False,True,True])]
print(b)
[[1 2 3]
[4 5 6]
[7 8 9]]
[[2 3]
[8 9]]