how to sum over columns in python

To sum over columns in Python, you can use the NumPy library which provides efficient array manipulation. Here's how you can do it:

main.py
import numpy as np

# Create a 2D array
array = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])

# Sum over columns
column_sums = np.sum(array, axis=0)

print(column_sums)
202 chars
12 lines

In this example, we have a 2D array with 3 columns. By using np.sum, we specify axis=0 to perform the summation operation along each column. The resulting column sums are stored in the column_sums variable.

Output:

main.py
[12 15 18]
11 chars
2 lines

Thus, the sum of the first column is 12, sum of the second column is 15, and sum of the third column is 18.

related categories

gistlibby LogSnag