1

How can I add column values in a two dimenstional array? For example

[[11.9, 12.2, 12.9],
 [15.3, 15.1, 15.1], 
 [16.3, 16.5, 16.5],
 [17.7, 17.5, 18.1]]

I want it to result to:

[61.2,61.3,62.6]

I have tried this so far:

Btotals.append(sum(float(x)) for x in zip(totals))

However it gave me this:

[<generator object <genexpr> at 0x02A42878>]
3
  • [sum(x) for x in zip(*totals)] Commented Nov 6, 2015 at 3:29
  • @CSZ thanks for the help.. Commented Nov 6, 2015 at 3:31
  • Is there a reason you can't use numpy for this? With numpy it would be: numpy.sum(a, axis=0). Commented Nov 6, 2015 at 3:57

2 Answers 2

1

You need to unpack the argument to zip first.

a = [[11.9, 12.2, 12.9],
    [15.3, 15.1, 15.1], 
    [16.3, 16.5, 16.5],
    [17.7, 17.5, 18.1]]
result = [sum(x) for x in zip(*a)]
>>> [61.2, 61.3, 62.6]
Sign up to request clarification or add additional context in comments.

2 Comments

If you want to do anything more complicated, I agree with @Akavall, numpy would be the way to go.
how can I get the sum of square of each element in a?
0

If array is a variable containing your 2d array, try

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.