【问题标题】:how to find the sum and average of multiple columns in pandas如何在熊猫中找到多列的总和和平均值
【发布时间】:2019-10-30 00:07:20
【问题描述】:

我有一个包含 4 列的数据框。数据框如下所示:

      date  sell price      cost price            discount
2019-10-13    2000            2000               0
2019-10-21    3000            3000               0

我需要找到 cost pricesell price 两列的总和和平均值。输出应该是这样的:

                total      avg           
sell price       5000      2500          
cost price       5000      2500   

我怎样才能得到这个?

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

使用DataFrame.agg:

  new_df=df[['sell_price', 'cost_price']].agg(['sum','mean']).T.rename(columns={'sum':'total','mean':'Avg'})
print(new_df)

             total     Avg
sell_price  5000.0  2500.0
cost_price  5000.0  2500.0

【讨论】:

  • 请立即查看
【解决方案2】:

试试这个:

df[["sell price", "cost price"]].agg( ["sum", "mean"]).stack().unstack(0).rename(columns={"sum": "total", "mean": "avg"})

输出:

            total     avg
sell price  5000.0  2500.0
cost price  5000.0  2500.0

[Program finished]

【讨论】:

    【解决方案3】:

    使用聚合应该做到这一点。

    df.aggregate({"cost_price":['sum','mean'],"sell_price":['sum','mean']})
    

    [更新] 为什么它不起作用?有什么错误可以看吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      • 2020-09-24
      • 1970-01-01
      • 2015-10-09
      相关资源
      最近更新 更多