簡體   English   中英

在 dataframe 的特定列上的 sum()

[英]sum() on specific columns of dataframe

我無法弄清楚如何在最后添加新行。 最后一行需要對特定列執行 sum() 並划分其他 2 列。 雖然 DF 已應用過濾器來僅對特定行求和。

東風:

    Categ    CategID    col3      col4      col5      col6
0   Cat1     1          -65.90    -100.40   -26.91    23.79
1   Cat2     2          -81.91    -15.30    -16.00    10.06
2   Cat3     3          -57.70    -18.62      0.00    0.00

我希望 output 像這樣:

3   Total              -123.60   -119.02    -26.91    100*(-119.02/-26.91)

col3,col4,col5 將具有 sum(),而 col6 將是上述公式。

如果 [CategID]==2,則不包括在 TOTAL 中

通過使用.query(),我幾乎可以得到它,就像這樣:

#tg 是一個列表

df.loc['Total'] = df.query("categID in @tg").sum()

但是有了上面我不能有像這樣的 'col6' 100*(col4.sum() / col5.sum()) ,因為它們都是 sum() 。

然后我嘗試了這樣的系列,但我不明白如何應用 filter.where()

s = pd.Series(  [df['col3'].sum()\
                ,df['col4'].sum()\
                ,df['col5'].sum()\
                ,100*(df['col4'].sum()/df['col5'].sum())\
                ,index = ['col3','col4','col5','col6'])
df.loc['Total'] = s.where('tag1' in tg)

使用上面的 Series() 有效,直到我 add.where() 這給出了錯誤: ValueError: Array conditional must be same shape as self

那么,我是否可以使用第一種方法 using.query() 來完成此操作,只是以某種方式修改 TOTAL 中的一個列? 否則我在第二種方法中做錯了什么。 where()

謝謝

IIUC,你可以試試:

s = df.mask(df['CategID'].eq(2)).drop("CategID",1).sum()
s.loc['col6'] = 100*(s['col4'] / s['col5'])
df.loc[len(df)] = s

df = df.fillna({'Categ':'Total',"CategID":''})

print(df)

   Categ CategID    col3    col4   col5        col6
0   Cat1       1  -65.90 -100.40 -26.91   23.790000
1   Cat2       2  -81.91  -15.30 -16.00   10.060000
2   Cat3       3  -57.70  -18.62   0.00    0.000000
3  Total         -123.60 -119.02 -26.91  442.289112

暫無
暫無

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

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