I have a Python array, like so:
[[1,2,3],
[1,2,3]]
I can add the row by doing sum(array[i])
, how can I sum a column, using a
I think the easiest way is this:
sumcolumn=data.sum(axis=0)
print (sumcolumn)
You may be interested in numpy, which has more advanced array features. One of which is to easily sum a column:
from numpy import array
a = array([[1,2,3],
[1,2,3]])
column_idx = 1
a[:, column_idx].sum() # ":" here refers to the whole array, no filtering.
Try this:
a = [[1,2,3],
[1,2,3]]
print [sum(x) for x in zip(*a)]
zip function description
[sum(row[i] for row in array) for i in range(len(array[0]))]
That should do it. len(array[0])
is the number of columns, so i
iterates through those. The generator expression row[i] for row in array
goes through all of the rows and selects a single column, for each column number.
You don't need a loop, use zip() to transpose the list, then take the desired column:
sum(list(zip(*data)[i]))
(Note in 2.x, zip()
returns a list, so you don't need the list()
call).
Edit: The simplest solution to this problem, without using zip()
, would probably be:
column_sum = 0
for row in data:
column_sum += row[i]
We just loop through the rows, taking the element and adding it to our total.
This is, however, less efficient and rather pointless given we have built-in functions to do this for us. In general, use zip()
.
you can use zip()
:
In [16]: lis=[[1,2,3],
....: [1,2,3]]
In [17]: map(sum,zip(*lis))
Out[17]: [2, 4, 6]
or with a simple for loops:
In [25]: for i in xrange(len(lis[0])):
summ=0
for x in lis:
summ+=x[i]
print summ
....:
2
4
6