1

I have two relatively similar operations I'd like to figure out how to do.

The first is the simpler. I have a numpy array like

[[a,b,c,d],
 [e,f,g,h],
 [i,j,k,l]]

I would like to sum the columns to yield:

[6,12,18,24]

I know that I can do this with a for loop:

for i in range(0,ROW_LENGTH): #ROW_LENGTH defined elsewhere
    listsum[i]=list[:,i].sum()

But this can't be the pythonic way, can it?


The second task is I need to do something similar with a 3D array. I assume the solution to this will be similar. A simple example is:

[[[a,b,c],[d,e,f],[g,h,i]],
 [[j,k,l],[m,n,o],[p,q,r]],
 [[s,t,u],[v,w,x],[y,z,_]]]

Where the output should be:

[[a+j+s,b+k+t,c+l+u],[d+m+v,e+n+w,f+o+x],[g+p+y,h+q+z,i+r+_]]

I'm hopeful that understanding the technique for both of these will be a major boon, generally speaking, for how well I grasp python!

I'm going to link here to a separate question I'm asking for the same project:

3
  • 3
    Do you know about the axis parameter in np.sum? It allows you to perform these operation very efficiently. Commented Oct 28, 2015 at 15:38
  • WOW. Yes. Exactly. So what I want is np.sum(list,axis=0), correct? Can you put this in answer form so I can upvote and select? This also solves the other problem I was going to link to, which was with a product instead. THANK YOU! Commented Oct 28, 2015 at 15:53
  • Glad it helped - I've marked this question as a duplicate so it can help direct users to the correct answer. Commented Oct 28, 2015 at 16:03

1 Answer 1

0

In order to do that you can use the sum method of numpy.

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
a.sum(axis=0)

That should do the trick

Sign up to request clarification or add additional context in comments.

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.