簡體   English   中英

pandas Dataframe 中某些列的總和

[英]Sum of only certain columns in a pandas Dataframe

我有一個類似於下面的 dataframe。 我只需要將某些列的總和相加:Jan-16、Feb-16、Mar-16、Apr-16 和 May-16。 我在一個名為months_list的列表中有這些列

--------------------------------------------------------------------------------------
| Id               |  Name             | Jan-16 | Feb-16 | Mar-16 | Apr-16 | May-16   |
| 4674393          |  John Miller      |  0     | 1      | 1      | 1      | 1        |
| 4674395          |  Joe Smith        |  0     | 0      | 1      | 1      | 1        |
---------------------------------------------------------------------------------------

我的 output 應該如下所示:

--------------------------------------------------------------------------------------
| Id               |  Name             | Jan-16 | Feb-16 | Mar-16 | Apr-16 | May-16   |
| 4674393          |  John Miller      |  0     | 1      | 1      | 1      | 1        |
| 4674395          |  Joe Smith        |  0     | 0      | 1      | 1      | 1        |
|Total             |                   |  0     | 1      | 2      | 2      | 2        |
---------------------------------------------------------------------------------------

應該為我的months_list中的所有列引入一個名為“Total”的新行,並按列求和:Jan-16、Feb-16、Mar-16、Apr-16 和 May-16

我嘗試了以下方法,但沒有成功。 我得到了所有的 NaN 值

df.loc['Total',:]= df[months_list].sum(axis=1)

您使用了錯誤的axis參數值。

`axis=0`: Sums the column values
`axis=1`: Sums the row values

假設您的 df 為:

In [4]: df
Out[4]: 
        Id         Name  Jan-16  Feb-16  Mar-16  Apr-16  May-16
0  4674393  John Miller       0       1       1       1       1
1  4674395    Joe Smith       0       0       1       1       1

In [10]: months_list =['Jan-16', 'Feb-16', 'Mar-16', 'Apr-16', 'May-16']

你的代碼應該是:

In [12]: df.loc['Total'] = df[months_list].sum()

In [13]: df
Out[13]: 
              Id         Name  Jan-16  Feb-16  Mar-16  Apr-16  May-16
0      4674393.0  John Miller     0.0     1.0     1.0     1.0     1.0
1      4674395.0    Joe Smith     0.0     0.0     1.0     1.0     1.0
Total        NaN          NaN     0.0     1.0     2.0     2.0     2.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM