How to sum values of particular rows in pandas?

倾然丶 夕夏残阳落幕 提交于 2019-12-24 02:02:40

问题


I am not much familiar with Python yet. I have a pandas data frame that looks like this:

          0         1     2     3
55   Alice   12896399     8    45
45   Bob     16891982     0     0
90   Cybill   1800407     1     1
05   Alice   12896399   100   200
33   Bob     16891982   0.5     0
42   Bob     16891982  -1.5  -0.5
46   Bob     16891982     1     0
99   Cybill   1800407  0.00  0.00

How can i sum the values of columns 2 and 3 to get a result for each person? Like this:

   Alice     108    245
   Bob       0     -0.5
   Cybill    1     1

Thank you in advance for your reply.


回答1:


IIUC you can groupby and sum on the cols of interest:

In [13]:
df.groupby('0')[['2','3']].sum()

Out[13]:
            2      3
0                   
Alice   108.0  245.0
Bob       0.0   -0.5
Cybill    1.0    1.0


来源:https://stackoverflow.com/questions/38327613/how-to-sum-values-of-particular-rows-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!