How to sum values of particular rows in pandas?

2019-07-08 02:30发布

问题:

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