# 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]]
``````