### NumPy 入门教程

Lemeng_study · 更新于 2020-06-08

# 高级索引

Numpy 比一般的 Python 序列提供更多的索引方式。除了前面章节介绍的用整数和切片的索引外，本节深入介绍布尔型索引和花式索引。

## 1. 布尔型索引

### 1.1 比较运算符与布尔型数组

#### 案例

``````data = np.random.randn(7,4)
data
out:
array([[-0.79578969, -0.73156773,  0.60648318, -0.57213653],
[ 0.03461754, -0.91921724, -1.51730244,  0.68583205],
[-0.0584198 , -0.92494003, -0.08106442, -1.44821654],
[-0.76501214,  2.01128245,  1.0350961 ,  0.81014769],
[-0.71850433, -1.613115  , -0.23420344,  0.61378525],
[-1.06667762,  1.11845542,  1.68075202,  0.25989931],
[-0.80773979, -0.37137009,  0.45941405, -0.57604566]])
``````

``````names = np.array(['Ben','Tom','Ben','Jeremy','Jeremy','Tom','Ben'])
names
out:
array(['Ben', 'Tom', 'Ben', 'Jeremy', 'Jeremy', 'Tom', 'Ben'], dtype='<U6')
``````

``````data > 0
out:
array([[False, False,  True, False],
[ True, False, False,  True],
[False, False, False, False],
[False,  True,  True,  True],
[False, False, False,  True],
[False,  True,  True,  True],
[False, False,  True, False]])
``````

``````(data>-1) & (data < 1)
out:
array([[ True,  True,  True,  True],
[ True,  True, False,  True],
[ True,  True,  True, False],
[ True, False, False,  True],
[ True, False,  True,  True],
[False, False, False,  True],
[ True,  True,  True,  True]])
``````

### 1.2 比较运算符与布尔型索引

#### 案例

names中的每一个名字，和data的每一行是一一对应的关系。因此可以快速地选择出Ben的相关信息：

``````data[names=='Ben']
out:
array([[-0.79578969, -0.73156773,  0.60648318, -0.57213653],
[-0.0584198 , -0.92494003, -0.08106442, -1.44821654],
[-0.80773979, -0.37137009,  0.45941405, -0.57604566]])
``````

``````data[(names=='Ben') | (names=='Tom')]
out:
array([[-0.79578969, -0.73156773,  0.60648318, -0.57213653],
[ 0.03461754, -0.91921724, -1.51730244,  0.68583205],
[-0.0584198 , -0.92494003, -0.08106442, -1.44821654],
[-1.06667762,  1.11845542,  1.68075202,  0.25989931],
[-0.80773979, -0.37137009,  0.45941405, -0.57604566]])
``````

``````array([[-0.79578969, -0.73156773],
[ 0.03461754, -0.91921724],
[-0.0584198 , -0.92494003],
[-1.06667762,  1.11845542],
[-0.80773979, -0.37137009]])
``````

``````data[data > 0]
out:
array([0.60648318, 0.03461754, 0.68583205, 2.01128245, 1.0350961 ,
0.81014769, 0.61378525, 1.11845542, 1.68075202, 0.25989931,
0.45941405])
``````

## 2. 花式索引

### 2.1 使用一维整型数组作为索引

#### 案例

``````names[[4,3,2,1]]
out:
array(['Jeremy', 'Jeremy', 'Ben', 'Tom'], dtype='<U6')
``````

``````names[[-1,-2,-3,-4]]
out:
array(['Ben', 'Tom', 'Jeremy', 'Jeremy'], dtype='<U6')
``````

#### 案例

``````data[[3,1]]
out:
array([[-0.76501214,  2.01128245,  1.0350961 ,  0.81014769],
[ 0.03461754, -0.91921724, -1.51730244,  0.68583205]])
``````

### 2.2 传入多组索引序列

#### 案例

``````data[[3,1,2],[0,2,1]]
out:
array([-0.76501214, -1.51730244, -0.92494003])
``````

#### 案例

``````data[[3,1,2]][:,[0,2,1]]
out:
array([[-0.76501214,  1.0350961 ,  2.01128245],
[ 0.03461754, -1.51730244, -0.91921724],
[-0.0584198 , -0.08106442, -0.92494003]])
``````