除了for循环,Numpy 还提供另外一种更为优雅的遍历方法。
apply_along_axis(func1d, axis, arr)Apply a function to 1-D slices along the given axis.
【例】
import numpy as npx = 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.5y = 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.]
