基礎操作
import numpy as np
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x[1:7:2] # start:end:step
array([1, 3, 5])
x[-2:10]
array([8, 9])
x[-3:3:-1] # 逆序取值 常規(guī)逆序輸出 [::-1]
array([7, 6, 5, 4])
x[5:]
array([5, 6, 7, 8, 9])
# 多維切片
x = np.array([[[1],[2],[3]], [[4],[5],[6]]])
x.shape
(2, 3, 1)
x[1:2] # [:,:,:] ":",對應每一維度潘悼, 單獨維度可以進行 一維操作 :::
array([[[4],
[5],
[6]]])
x[..., 0]
array([[1, 2, 3],
[4, 5, 6]])
x[:, np.newaxis, :, :].shape # 添加維度
(2, 1, 3, 1)
x = np.array([[1, 2], [3, 4], [5, 6]])
x[[0, 1, 2], [0, 1, 0]] # 按位置取值
array([1, 4, 5])
x = np.array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
rows = np.array([[0, 0],
[3, 3]], dtype=np.intp)
columns = np.array([[0, 2],
[0, 2]], dtype=np.intp)
x[rows, columns]
array([[ 0, 2],
[ 9, 11]])
rows = np.array([0, 3], dtype=np.intp)
columns = np.array([0, 2], dtype=np.intp)
rows[:, np.newaxis]
array([[0],
[3]], dtype=int64)
x[rows[:, np.newaxis], columns]
array([[ 0, 2],
[ 9, 11]])
x[np.ix_(rows, columns)]
array([[ 0, 2],
[ 9, 11]])
# 混合索引
x[1:2, 1:3]
array([[4, 5]])
x[1:2, [1, 2]]
array([[4, 5]])
布爾索引
x = np.array([[1., 2.], [np.nan, 3.], [np.nan, np.nan]])
x[~np.isnan(x)]
array([1., 2., 3.])
x = np.array([1., -1., -2., 3])
x[x < 0] += 20
x
array([ 1., 19., 18., 3.])
x = np.array([[0, 1], [1, 1], [2, 2]])
rowsum = x.sum(-1)
x[rowsum <= 2, :]
array([[0, 1],
[1, 1]])
x = np.array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
rows = (x.sum(-1) % 2) == 0
rows
array([False, True, False, True])
columns = [0, 2]
x[np.ix_(rows, columns)]
array([[ 3, 5],
[ 9, 11]])
rows = rows.nonzero()[0]
x[rows[:, np.newaxis], columns]
array([[ 3, 5],
[ 9, 11]])
x = np.zeros((2,2), dtype=[('a', np.int32), ('b', np.float64, (3,3))])
x['a'].shape
(2, 2)
x['a'].dtype
dtype('int32')
x['b'].shape
(2, 2, 3, 3)
x['b'].dtype
dtype('float64')