user
In Python, how to sum columns of a NumPy array?
alphonsio

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.

Example:

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)

Output:

[12 15 18]

Explanation:

  • np.sum(arr, axis=0) sums the elements along the rows, producing a sum for each column.
    • Column 1 sum: 1 + 4 + 7 = 12
    • Column 2 sum: 2 + 5 + 8 = 15
    • Column 3 sum: 3 + 6 + 9 = 18

Summary:

  • axis=0 means summing along the rows, resulting in the sum of each column.
  • If you wanted to sum the rows instead, you would use axis=1.