How to sum columns of an array in Python How to sum columns of an array in Python arrays arrays

How to sum columns of an array in Python


zip and sum can get that done:

Code:

[sum(x) for x in zip(*input_val)]

zip takes the contents of the input list and transposes them so that each element of the contained lists is produced at the same time. This allows the sum to see the first elements of each contained list, then next iteration will get the second element of each list, etc...

Test Code:

input_val = [[1, 2, 3, 4, 5],             [1, 2, 3, 4, 5],             [1, 2, 3, 4, 5]]print([sum(x) for x in zip(*input_val)])

Results:

[3, 6, 9, 12, 15]


In case you decide to use any library, numpy easily does this:

np.sum(input_val,axis=0)


You may also use sum with zip within the map function:

# In Python 3.x >>> list(map(sum, zip(*input_val)))[3, 6, 9, 12, 15]# explicitly type-cast it to list as map returns generator expression# In Python 2.x, explicit type-casting to list is not needed as `map` returns list>>> map(sum, zip(*input_val))[3, 6, 9, 12, 15]