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?
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
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With