读书笔记 numpy入门 第7章 花式索引

https://github.com/jakevdp/PythonDataScienceHandbook

https://www.numpy.org.cn

Fancy indexing作用-获取数组中特定元素

快速获得并修改复杂的数组值得子数据集。

传递的是索引数组,而不是单个标量。

单个维度

1
2
3
4
5
6
7
8
9
10
11
import numpy as np
rand = np.random.RandomState(42)

x = rand.randint(100, size=10)
print(x)

[51 92 14 71 60 20 82 86 74 74]

[x[3], x[7], x[2]]

[71, 86, 14]
1
2
3
4
5
6


ind = [3, 7, 4]
x[ind]

array([71, 86, 60])
1
2
3
4
5
6
7
8
# 利用花哨的索引,结果的形状与索引数组的形状一致,而不是与被索引数组的形状一致

ind = np.array([[3, 7],
[4, 5]])
x[ind]

array([[71, 86],
[60, 20]])

多维度

1
2
3
4
5
6
7
8
9
10
11
12
X = np.arange(12).reshape((3, 4))
X

array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

row = np.array([0, 1, 2])
col = np.array([2, 1, 3])
X[row, col]

>>> array([ 2, 5, 11])