### NumPy 入门教程

Lemeng_study · 更新于 2020-05-26

# Numpy 的索引与切片

Python 的内置容器对象，例如列表，可以通过索引或切片来访问和修改。这在 ndarray 对象中也一样，ndarray 对象中的元素遵循基于零的索引，常用的索引方式：元素访问、切片索引、布尔型索引。

## 1. 元素访问

### 1.1 单一元素访问

#### 案例

``````arr = np.arange(10)
``````
``````arr
Out:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
``````
``````arr[4]
Out:
4
``````

``````arr[-1]
Out:
9
``````

## 2. 切片索引

### 2.1 基本切片

#### 案例

``````arr[[0, -1]]
Out:
array([0, 9])
``````

``````arr[0: -1: 2]
Out:
array([0, 2, 4, 6, 8])
``````

``````arr[1: -1: 2]
Out:
array([1, 3, 5, 7])
``````
``````arr[1: : 2]
Out:
array([1, 3, 5, 7, 9])
``````

### 2.2 多维数组切片索引

#### 案例

``````arr_2d = np.arange(16).reshape(4,4)
Out:
array([[ 0,  1,  2,  3],
[ 4,  5,  6,  7],
[ 8,  9, 10, 11],
[12, 13, 14, 15]])
``````

`arr_2d` 构造一个连续切片：

``````arr_2d[0][1:3]
Out:
array([1, 2])
``````

``````arr_2d[0, 1:3]
Out:
array([1, 2])
``````

``````arr_2d[0:2, 1:3]
Out:
array([[1, 2],
[5, 6]])
``````

``````arr_2d[:, 1:3]
Out:
array([[ 1,  2],
[ 5,  6],
[ 9, 10],
[13, 14]])
``````

## 3. 布尔型索引

#### 案例

``````arr_2d[[True, True, False, False]]
Out:
array([[0, 1, 2, 3],
[4, 5, 6, 7]])
``````

``````arr_2d[:, [True, True, False, False]]
Out:
array([[ 0,  1],
[ 4,  5],
[ 8,  9],
[12, 13]])
``````