简体   繁体   English

总和 DataFrame 行和列

[英]sum DataFrame rows and columns

Suppose I have a dataframe like so:假设我有一个 dataframe 像这样:

     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.例如,我想总结行和列的 4 个元素的值。 This would give me 1+5+4+7=17 and 5+9+3+1=18, 2+3+4+6=15, ...这会给我 1+5+4+7=17 和 5+9+3+1=18, 2+3+4+6=15, ...

output output

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

How do I do this in pandas?如何在 pandas 中执行此操作?

Let us try einsum让我们试试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 :我们可以尝试 numpy 的reshapesum

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

Output: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM