Skip to content Skip to sidebar Skip to footer

Sum Matrix Columns In Python

I can sum the items in column zero fine. But where do I change the code to sum column 2, or 3, or 4 in the matrix? I'm easily stumped. def main(): matrix = [] for i in ra

Solution 1:

numpy could do this for you quite easily:

defsumColumn(matrix):
    return numpy.sum(matrix, axis=1)  # axis=1 says "get the sum along the columns"

Of course, if you wanted do it by hand, here's how I would fix your code:

def sumColumn(m):
    answer = []
    forcolumninrange(len(m[0])):
        t =0forrowin m:
            t +=row[column]
        answer.append(t)
    return answer

Still, there is a simpler way, using zip:

defsumColumn(m):
    return [sum(col) for col inzip(*m)]

Solution 2:

One-liner:

column_sums = [sum([row[i] forrowin M]) for i inrange(0,len(M[0]))]

also

row_sums = [sum(row) forrowin M]

for any rectangular, non-empty matrix (list of lists) M. e.g.

>>>M = [[1,2,3],\>>>    [4,5,6],\>>>    [7,8,9]]>>>>>>[sum([row[i] for row in M]) for i inrange(0,len(M[0]))]
[12, 15, 18] 
>>>[sum(row) for row in M]
[6, 15, 24]

Solution 3:

Here is your code changed to return the sum of whatever column you specify:

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

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

Solution 4:

To get the sum of all columns in the matrix you can use the below python numpy code:

matrixname.sum(axis=0)

Solution 5:

import numpy as np
np.sum(M,axis=1)

where M is the matrix

Post a Comment for "Sum Matrix Columns In Python"