索引
一维数组
从一维数组开始,例如:
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
支持的索引模式如下:
- 单个数字索引:
>>> a[2]
2
-
切片索引:
- 给定起始和终止位置
>>> a[1:3] array([1, 2])
- 不给定起始 or 终止位置,默认起始位置是0,终止位置是最后
>>> a[:2] array([0, 1]) >>> a[3:] array([3, 4])
- 给定起始和终止位置
-
布尔索引:
>>> bool_idx = a > 3
>>> bool_idx
array([False, False, False, False, True])
>>> a[bool_idx]
array([4])
or
>>> a[a > 3]
array([4])
>>> idx1 = a >=1
>>> idx2 = a < 5
>>> idx = idx1 & idx2
>>> idx
array([False, True, True, True, True])
>>> a[idx]
array([1, 2, 3, 4])
- 花式索引
花式索引可以简单的理解为用一个数组做索引
>>> a[[0, 1, 3]]
array([0, 1, 3])
二维数组
扩展到二维数组:
>>> a = np.random.randint(0, 100, size=(8, 5))
>>> a
array([[15, 50, 21, 82, 19],
[47, 57, 31, 31, 32],
[20, 63, 58, 6, 64],
[20, 23, 36, 42, 28],
[94, 16, 66, 80, 13],
[21, 37, 8, 52, 48],
[67, 80, 38, 37, 3],
[ 9, 93, 43, 72, 32]])
- 单个数字索引
>>> a[2]
array([20, 63, 58, 6, 64])
>>> a[2, 3]
6
- 切片索引
>>> a[:2] # 行切片
array([[15, 50, 21, 82, 19],
[47, 57, 31, 31, 32]])
>>> a[:, :1] # 列切片
array([[15],
[47],
[20],
[20],
[94],
[21],
[67],
[ 9]])
>>> a[2:4, 1:3] # 行切片+列切片
array([[63, 58],
[23, 36]])
- 布尔索引
>>> idx1 = a > 90
>>> idx2 = a < 10
>>> idx = idx1 | idx2
>>> a[idx]
array([ 6, 94, 8, 3, 9, 93])
- 花式索引
>>> a[[0, 3, 5, 2, 4]]
array([[15, 50, 21, 82, 19],
[20, 23, 36, 42, 28],
[21, 37, 8, 52, 48],
[20, 63, 58, 6, 64],
[94, 16, 66, 80, 13]])
>>> a[:, [0, 3, 2, 4]]
array([[15, 82, 21, 19],
[47, 31, 31, 32],
[20, 6, 58, 64],
[20, 42, 36, 28],
[94, 80, 66, 13],
[21, 52, 8, 48],
[67, 37, 38, 3],
[ 9, 72, 43, 32]])
>>> a[[0, 2], [3, 4]]
array([82, 64])
未完待续…