NumPy - 切片和索引

`ndarray`对象的内容可以通过索引或切片来访问和修改，就像 Python 的内置容器对象一样。

示例 1

``````import numpy as np
a = np.arange(10)
s = slice(2,7,2)
print a[s]
``````

``````[2  4  6]
``````

示例 2

``````import numpy as np
a = np.arange(10)
b = a[2:7:2]
print b
``````

``````[2  4  6]
``````

示例 3

``````# 对单个元素进行切片
import numpy as np

a = np.arange(10)
b = a[5]
print b
``````

``````5
``````

示例 4

``````# 对始于索引的元素进行切片
import numpy as np
a = np.arange(10)
print a[2:]
``````

``````[2  3  4  5  6  7  8  9]
``````

示例 5

``````# 对索引之间的元素进行切片
import numpy as np
a = np.arange(10)
print a[2:5]
``````

``````[2  3  4]
``````

示例 6

``````import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print a
# 对始于索引的元素进行切片
print  '现在我们从索引 a[1:] 开始对数组切片'
print a[1:]
``````

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

[[3 4 5]
[4 5 6]]
``````

示例 7

``````# 最开始的数组
import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print  '我们的数组是：'
print a
print  '\n'
# 这会返回第二列元素的数组：
print  '第二列的元素是：'
print a[...,1]
print  '\n'
# 现在我们从第二行切片所有元素：
print  '第二行的元素是：'
print a[1,...]
print  '\n'
# 现在我们从第二列向后切片所有元素：
print  '第二列及其剩余元素是：'
print a[...,1:]
``````

``````我们的数组是：
[[1 2 3]
[3 4 5]
[4 5 6]]

[2 4 5]

[3 4 5]

[[2 3]
[4 5]
[5 6]]
``````