Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum DataFrame rows and columns

Tags:

python

pandas

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?

like image 658
ulduz Avatar asked Jul 16 '20 16:07

ulduz


2 Answers

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
like image 157
BENY Avatar answered Oct 20 '22 10:10

BENY


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]])
like image 42
Quang Hoang Avatar answered Oct 20 '22 09:10

Quang Hoang