NumPy - 高级索引

整数索引

示例 1

``````import numpy as np

x = np.array([[1,  2],  [3,  4],  [5,  6]])
y = x[[0,1,2],  [0,1,0]]
print y
``````

``````[1  4  5]
``````

示例 2

``````import numpy as np
x = np.array([[  0,  1,  2],[  3,  4,  5],[  6,  7,  8],[  9,  10,  11]])
print  '我们的数组是：'
print x
print  '\n'
rows = np.array([[0,0],[3,3]])
cols = np.array([[0,2],[0,2]])
y = x[rows,cols]
print  '这个数组的每个角处的元素是：'
print y
``````

``````我们的数组是：
[[ 0  1  2]
[ 3  4  5]
[ 6  7  8]
[ 9 10 11]]

[[ 0  2]
[ 9 11]]
``````

示例 3

``````import numpy as np
x = np.array([[  0,  1,  2],[  3,  4,  5],[  6,  7,  8],[  9,  10,  11]])
print  '我们的数组是：'
print x
print  '\n'
# 切片
z = x[1:4,1:3]
print  '切片之后，我们的数组变为：'
print z
print  '\n'
# 对列使用高级索引
y = x[1:4,[1,2]]
print  '对列使用高级索引来切片：'
print y
``````

``````我们的数组是：
[[ 0  1  2]
[ 3  4  5]
[ 6  7  8]
[ 9 10 11]]

[[ 4  5]
[ 7  8]
[10 11]]

[[ 4  5]
[ 7  8]
[10 11]]
``````

布尔索引

示例 1

``````import numpy as np
x = np.array([[  0,  1,  2],[  3,  4,  5],[  6,  7,  8],[  9,  10,  11]])
print  '我们的数组是：'
print x
print  '\n'
# 现在我们会打印出大于 5 的元素
print  '大于 5 的元素是：'
print x[x >  5]
``````

``````我们的数组是：
[[ 0  1  2]
[ 3  4  5]
[ 6  7  8]
[ 9 10 11]]

[ 6  7  8  9 10 11]
``````

示例 2

``````import numpy as np
a = np.array([np.nan,  1,2,np.nan,3,4,5])
print a[~np.isnan(a)]
``````

``````[ 1.   2.   3.   4.   5.]
``````

示例 3

``````import numpy as np
a = np.array([1,  2+6j,  5,  3.5+5j])
print a[np.iscomplex(a)]
``````

``````[2.0+6.j  3.5+5.j]
``````