【问题标题】:how to calculate mean and median based on label of a column in python如何根据python中列的标签计算平均值和中位数
【发布时间】:2020-12-10 17:04:46
【问题描述】:

我有一个大数据框,显示如下:

price   type      status
2       shoes      none
3       clothes    none
6       clothes    none
3       shoes      none
4       shoes      none
6       shoes      none
2       clothes    none
3       shoes      none
6       clothes    none
8       clothes    done

基本上,每当“状态”写入完成时,我想根据“类型”计算平均值和中位数。 到目前为止,我所做的是首先根据“完成”状态创建一个组,然后像下面的脚本一样计算组的平均值和中位数:

g = df['status'].eq('done').iloc[::-1].cumsum().iloc[::-1]
grouper = df.groupby(g)
df_statistics = grouper.agg(
               mean = ('price', 'mean')
              ,median = ('price', 'median')
)
df_freq = df.groupby(g).apply(lambda x: x['price'].value_counts().idxmax())

如何为“类型”再添加一个参数,这样脚本也会根据“类型”估计每个组的中位数。

谢谢

【问题讨论】:

标签: python pandas statistics mean median


【解决方案1】:

我认为您需要将列名传递给列表,然后传递给groupby

grouper = df.groupby([g, 'type'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-03
    • 2015-06-28
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    相关资源
    最近更新 更多