[英]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.