John Finkelstein
John Finkelstein

Reputation: 31

Find the sum of a column in a python matrix?

I know how to do the sum of a row like this: row = [sum(row) for row in Matrix], but how to find the sum of a column in a python matrix?

If I have this matrix:

Matrix =[[0, 2, 2],
         [0, 2, 2], 
         [0, 0, 2]]

It should make 3 values, they are: 0,4, and 6.

Upvotes: 2

Views: 9050

Answers (6)

import numpy as np
a = np.array([[1, 2, 3],
              -1, 2, 6])

print(a.cumsum(axis = 0))

Output:

>>> np.array([[1, 2, 3],
              [0, 4, 9]])

Last field is sum of columns

If you want to get sum of field just put "1" instead "0" in axis.

In [121]: a.cumsum(axis = 1)
Out[121]:
array([[ 1,  3,  6],
       [-1,  1,  7]], dtype=int32)

Upvotes: 0

Wojciech Moszczyński
Wojciech Moszczyński

Reputation: 3187

Sum of the rows in matrix you can do in this way. We create simple matrix:

import pandas as pd

cc =[100, 0, 0, 0]
aaa = [80, 9, 1, 1]
fff = [10, 0, 8, 0]
hhh = [10, 1, 1, 9]

df = pd.DataFrame({'A': cc, 'B': aaa,'C': fff,'D': hhh})
matrix = df.values
matrix

sum of the rows

sumR = matrix.sum(axis=1) 
sumR

array([200, 10, 10, 10])

sumR = list(sumR.flatten())
sumR

[200, 10, 10, 10]

sum of the columns

sumC = matrix.sum(axis=0) 
sumC

array([100, 91, 18, 21])

sumC = list(sumC.flatten())
sumC

[100, 91, 18, 21]

Upvotes: 0

Allen Qin
Allen Qin

Reputation: 19947

import numpy as np
Matrix =[[0, 2, 2],
         [0, 2, 2], 
         [0, 0, 2]]
np.asarray(Matrix).sum(axis=0)
Out[66]: array([0, 4, 6])

It's quite self explanatory but someone is asking to comment the code.

The code first casts the matrix to a numpy array and then sums the array colomn wise, which is what this question is about.

Upvotes: -1

BlooB
BlooB

Reputation: 965

Look here same question, great example codes. Look at the

def sumColumn(m, column):
    total = 0
    for row in range(len(m)):
        total += m[row][column]
    return total

column = 1
print("Sum of the elements in column", column, "is", sumColumn(matrix, column))

you can look and each time add one to the index so you look at the next column

or you can use zip:

def sumColumn(m):
    return [sum(col) for col in zip(*m)]

or simplere way from here:

sum(m[:,i]) for i in range(4)

Upvotes: 2

stanleyli
stanleyli

Reputation: 1477

A more Pythonic way than some of the other answers:

[sum(row[i] for row in Matrix) for i in range(len(Matrix[0]))]

Bit this is very inefficient in terms of cache performance. So try your best to avoid it, or transpose the matrix first if you need to perform this operation on the same matrix multiple times.

Upvotes: 1

kopo222
kopo222

Reputation: 127

From here

Try this, it sums the matrix by the specified column:

def sumColumn(m, column):
total = 0
for row in range(len(m)):
    total += m[row][column]
return total

column = 1
print("Sum of the elements in column", column, "is", sumColumn(matrix, column))

Upvotes: 0

Related Questions