ndarrays可以使用x[start:stop:step]的语法.
注意在切片的时候,stop是不包含在内的
import numpy as np
data=np.array([1,2,3,4])
data[0]
1
data[1]
2
data[0:1]
array([1])
data[0:2]
array([1, 2])
data[1:2]
array([2])
索引子矩阵
In[2]: import numpy as np
...: d=np.arange(1,26).reshape((5,5))
...:
索引行
索引连续多行与索引任意多行
In[3]: d[1]
Out[3]: array([ 6, 7, 8, 9, 10])
In[4]: d[1,:]
Out[4]: array([ 6, 7, 8, 9, 10])
索引列
索引连续多列与索引任意多列
In[5]: d[:,1]
Out[5]: array([ 2, 7, 12, 17, 22])
索引值
索引连续多值索引任意多值
In[6]: d[1][2]
Out[6]: 8
In[7]: d[1,2]
Out[7]: 8
In[8]: d[[1,2,3],[1,3,4]] # 一次索引多个值
Out[8]: array([ 7, 14, 20])
条件索引
条件索引的原理是布尔索引,所以关键是要找到对应的布尔矩阵
In[2]: import numpy as np
...:
...: test = np.array([[1,2,3,4],[4,3,2,1]])
...:
In[3]: test
Out[3]:
array([[1, 2, 3, 4],
[4, 3, 2, 1]])
In[4]: test>2
Out[4]:
array([[False, False, True, True],
[ True, True, False, False]], dtype=bool)
In[5]: (test==2) | (test==3) # 不能使用all
Out[5]:
array([[False, True, True, False],
[False, True, True, False]], dtype=bool)
In[6]: np.isin(test,[2,3])
Out[6]:
array([[False, True, True, False],
[False, True, True, False]], dtype=bool)