To sum the columns of a NumPy array, the best option is to use the numpy.sum() method by specifying the axis option:
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4], [5, 6]])
>>> a.sum(axis=0)
array([ 9, 12])
In Python, you can sum the columns of a NumPy array using the numpy.sum() function along with the axis parameter. To sum the columns, you need to set axis=0.
import numpy as np
# Create a NumPy array
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Sum the columns (axis=0)
column_sum = np.sum(arr, axis=0)
print(column_sum)
[12 15 18]
np.sum(arr, axis=0) sums the elements along the rows, producing a sum for each column.1 + 4 + 7 = 122 + 5 + 8 = 153 + 6 + 9 = 18axis=0 means summing along the rows, resulting in the sum of each column.axis=1.