MarJamRob
MarJamRob

Reputation: 3465

How can I sum a column of a list?

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 double for loop?

I.E. for the first column, I could get 2, then 4, then 6.

Upvotes: 18

Views: 76610

Answers (8)

martineau
martineau

Reputation: 123393

Using a for loop (in a generator expression):

data = [[1,2,3],
        [1,2,3]]

column = 1
print(sum(row[column] for row in data))  # -> 4

Upvotes: 32

Mark Ransom
Mark Ransom

Reputation: 308101

[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.

Upvotes: 5

Arunim sharma
Arunim sharma

Reputation: 29

You can use numpy:

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

Upvotes: 0

icehand
icehand

Reputation: 21

I think the easiest way is this:

sumcolumn=data.sum(axis=0)

print (sumcolumn)

Upvotes: 2

monkut
monkut

Reputation: 43832

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.

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

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

Upvotes: 0

Gareth Latty
Gareth Latty

Reputation: 88977

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().

Upvotes: 5

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

Try this:

a = [[1,2,3],
     [1,2,3]]

print [sum(x) for x in zip(*a)]

zip function description

Upvotes: 7

Related Questions