python - sum() 在数据框的特定列上
问题描述
我无法弄清楚如何在最后添加新行。最后一行需要对特定列执行 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
我希望输出是这样的:
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()。
然后我尝试了这样的系列,但我不明白如何应用过滤器 .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() 有效,直到我添加 .where() 这给出了错误:
ValueError: Array conditional must be same shape as self
那么,我可以使用第一种方法完成此操作,使用 .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
推荐阅读
- php - PHP / Laravel - 在 JSON 中发送数组返回空
- javascript - 捆绑失败:错误:无法从“/workspace/reactnative”中找到模块“babel-preset-react-native”
- logging - 是否可以根据日志标记将 logback 日志分离到单独的附加程序?
- python - 如何将 tf.nn.top_k 中的索引与 tf.gather_nd 一起使用?
- c# - 使用其他类的 GetEnumerator 时如何处理 foreach 空异常?
- c++ - 更改提交按钮的位置(windows wrap credential provider)
- google-analytics - 非标准实施 Google Analytics
- reactjs - 无法在 React 中设置属性“不确定”的 null
- python - 在函数中打印返回值,Python
- c# - 如何使用asp.net通过gridview中的复选框删除多条记录