计算一个二维NumPy数组所有列的总和
让我们看看如何计算一个2维NumPy数组的所有列的总和。
示例 :
输入:
[[1, 2, 3, 4, 5],
[5, 6, 7, 8, 9],
[2, 1, 5, 7, 8],
[2, 9, 3, 1, 0]]
输出:
[10, 18, 18, 20, 22]
输入:
[[5, 4, 1, 7],
[0, 9, 3, 5],
[3, 2, 8, 6]]
输出:
[8, 15, 12, 18]
方法1:我们将使用sum()方法。我们将传递参数axis = 0,以获得按列计算的总和。
# importing numpy
import numpy as np
# initialize the 2-d array
arr = np.array([[1, 2, 3, 4, 5],
[5, 6, 7, 8, 9],
[2, 1, 5, 7, 8],
[2, 9, 3, 1, 0]])
# calculating column wise sum
sum_2d = arr.sum(axis = 0)
# displaying the sum
print("Column wise sum is :\n", sum_2d)
输出 :
Column wise sum is :
[10 18 18 20 22]
方法2 :我们也可以使用numpy.einsum()方法,参数为’ij->j’。
# importing numpy
import numpy as np
# initialize the 2-d array
arr = np.array([[1, 2, 3, 4, 5],
[5, 6, 7, 8, 9],
[2, 1, 5, 7, 8],
[2, 9, 3, 1, 0]])
# calculating column wise sum
sum_2d = np.einsum('ij->j', arr)
# displaying the sum
print("Column wise sum is :\n", sum_2d)
输出 :
Column wise sum is :
[10 18 18 20 22]