7

Suppose I have a dataframe like so:

     a   b  c  d  e  f
1.   1   5  5  9  2  3
2.   4   7  3  1  4  6
3.   2   3  8  9  2  1 
4.   7   3  1  4  7  11
5.   8   5  4  9  0  3
6.   7   8  4  7  2  1

I want to sum up the values for 4 elements of rows and columns for example. This would give me 1+5+4+7=17 and 5+9+3+1=18 , 2+3+4+6=15 , ...

output

       a    b    c
   1.  17   18   15
   2.  18   22   21
   3.  28   27   6

How do I do this in pandas?

2 Answers 2

6

Let us try einsum

pd.DataFrame(np.einsum('ijkl->ik',df.values.reshape(3,2,3,2)))
Out[101]: 
    0   1   2
0  17  18  15
1  15  22  21
2  28  24   6
Sign up to request clarification or add additional context in comments.

1 Comment

Tried df.rolling(2,axis=1).sum().iloc[:,1::2].rolling(2).sum().iloc[1::2] but probably not as efficient as yours and Quang's. Learnt about einsum +1
5

We can try numpy's reshape and sum:

a = df.to_numpy()
a.reshape(df.shape[0]//2,2, df.shape[1]//2,2).sum((1,3))

Output:

array([[17, 18, 15],
       [15, 22, 21],
       [28, 24,  6]])

1 Comment

Was the reshape arbitrary and then you choose the appropriate sum axis? If not, how did you know how to reshape?

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.