0

Say, I have a numpy array like this:

[[ 1 2 3 5]
 [ 4 5 6 8]
 [ 7 8 9 11]]

I want to get the sum of (col 0+col 2) and (col1+col3) for each row. I know its probably elementary, but cant get it. Kindly help

3 Answers 3

2

Well yes it's pretty elementary once you know the assignment scheme of numpy arrays :

Let

    x = [[ 1 2 3 5]
         [ 4 5 6 8]
         [ 7 8 9 11]]

y1 = x[:,0]+x[:,2]    # Sum of columns 0 and 2
y1 = array([4,10,16])
y2 = x[:,1]+x[:,3]    # Sum of columns 1 and 3
y2 = array([7,13,19])
Sign up to request clarification or add additional context in comments.

1 Comment

So what if I have 1000 columns? Should we write 2000 lines of code for that?
2

This should do the trick:

import numpy as np
mat=np.arange(12).reshape(3,4)
A=np.sum(mat,axis=0)[0::2] 
B=np.sum(mat,axis=0)[1::2]

A = (col 0+col 2)
B = (col1 + col3)

1 Comment

Note, that I used the variable mat, which is different from your matrix. Just substitute mat in line 3 and 4 with the variable of your matrix.
0

Setup

Out[99]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Solution

#reshape the array to 2 columns, then sum columns, finally reshape it back to 2 columns.
a.reshape(-1,2).sum(1).reshape(-1,2)
Out[102]: 
array([[ 1,  5],
       [ 9, 13],
       [17, 21]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.