对二维数组切片
import numpy as np
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
print(x[-2:])
# [[26 27 28 29 30]
# [31 32 33 34 35]]
print(x[:-2])
# [[11 12 13 14 15]
# [16 17 18 19 20]
# [21 22 23 24 25]]
print(x[1:3, 2:4])
# [[18 19]
# [23 24]]
print(x[::2, ::2])
# [[11 13 15]
# [21 23 25]
# [31 33 35]]
print(x[::-1, :])
# [[31 32 33 34 35]
# [26 27 28 29 30]
# [21 22 23 24 25]
# [16 17 18 19 20]
# [11 12 13 14 15]]
print(x[:, ::-1])
# [[15 14 13 12 11]
# [20 19 18 17 16]
# [25 24 23 22 21]
# [30 29 28 27 26]
# [35 34 33 32 31]]
x[0::2, 1::3] = 0
print(x)
# [[11 0 13 14 0]
# [16 17 18 19 20]
# [21 0 23 24 0]
# [26 27 28 29 30]
# [31 0 33 34 0]]
dots 索引
使用…表示足够多的冒号来构建完整的索引列表。
import numpy as np
x = np.random.randint(1, 100, [2, 2, 3])
print(x)
# [[[59 71 46]
# [40 47 89]]
#
# [[88 33 78]
# [36 25 94]]]
print(x[1, ...])
# [[88 33 78]
# [36 25 94]]
print(x[..., 2])
# [[46 89]
# [78 94]]
整数数组索引
方括号内传入多个索引值,可以同时选择多个元素。
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
r = [0, 1, 2]
c = [2, 3, 4]
y = x[r, c]
print(y)
# [13 19 25]
# 行索引是 [0,0] 和 [4,4],而列索引是 [0,4] 和 [0,4]。
r = np.array([[0, 0], [4, 4]])
c = np.array([[0, 4], [0, 4]])
y = x[r, c]
print(y)
# [[11 15]
# [31 35]]
y = x[0:3, [1, 2, 2]]
print(y)
# [[12 13 13]
# [17 18 18]
# [22 23 23]]
numpy. take
numpy.take(a, indices, axis=None, out=None, mode=‘raise’) Take elements from an array along an axis.
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
r = [0, 1, 2]
print(np.take(x, r))
# [1 2 3]
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
r = [0, 1, -1]
print(np.take(x, r, axis=0))
# [[11 12 13 14 15]
# [16 17 18 19 20]
# [31 32 33 34 35]]
r = [0, 1, 2]
c = [2, 3, 4]
y = np.take(x, [r, c])
print(y)
# [[11 12 13]
# [13 14 15]]
布尔索引
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = x > 5
print(y)
# [False False False False False True True True]
print(x[x > 5])
# [6 7 8]
x = np.array([np.nan, 1, 2, np.nan, 3, 4, 5])
y = np.logical_not(np.isnan(x))
print(x[y])
# [1. 2. 3. 4. 5.]
数组迭代
apply_along_axis(func1d, axis, arr) Apply a function to 1-D slices along the given axis.
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
y = np.apply_along_axis(np.sum, 0, x)
print(y) # [105 110 115 120 125]
y = np.apply_along_axis(np.sum, 1, x)
print(y) # [ 65 90 115 140 165]
y = np.apply_along_axis(np.mean, 0, x)
print(y) # [21. 22. 23. 24. 25.]
y = np.apply_along_axis(np.mean, 1, x)
print(y) # [13. 18. 23. 28. 33.]
def my_func(x):
return (x[0] + x[-1]) * 0.5
y = np.apply_along_axis(my_func, 0, x)
print(y) # [21. 22. 23. 24. 25.]
y = np.apply_along_axis(my_func, 1, x)
print(y) # [13. 18. 23. 28. 33.]