我有一个具有以下形状的 numpy 数组:
(365L, 280L, 300L)
我想对第一个维度 (365) 的数组求和,以便得到 365 个值作为结果。
我可以做 np.sum(),但如何指定哪个轴?
--编辑:
答案的形状应该是:(365,)
请您参考如下方法:
NumPy 版本 >= 1.7
np.sum允许使用 整数元组 作为 axis 参数一次计算沿多个轴的总和:
import numpy as np
arr = ... # somearray
np.sum(arr, axis=(1, 2)) # along axis 1 and 2 (remember the first axis has index 0)
np.sum(arr, axis=(2, 1)) # the order doesn't matter
或者直接使用数组的sum方法:
arr.sum(axis=(1, 2))
后者仅在 arr 已经是一个 numpy 数组时有效。即使您的 arr 是 python-list,np.sum 也能正常工作。
NumPy 版本 <1.7:
使用元组作为 axis 参数的选项尚未实现,但您始终可以嵌套多个 np.sum 或 .sum调用:
np.sum(np.sum(arr, axis=1), axis=1) # Nested sums
arr.sum(axis=2).sum(axis=1) # identical but more "sequential" than "nested"
