【问题标题】:How to calculate aggregated summary statistics in Pandas dataframe如何计算 Pandas 数据框中的汇总汇总统计信息
【发布时间】:2019-08-18 16:38:39
【问题描述】:

我有一个类似这样的 Pandas 数据框:

>>> df = pd.DataFrame(data=np.array([['red', 'cup', 1.50], ['blue', 'jug', 2.40], ['red', 'cup', 1.75], ['blue', 'cup', 2.30]]),
...                   columns=['colour', 'item', 'price'])
>>> df
  colour item price
0    red  cup   1.5
1   blue  jug   2.4
2    red  cup  1.75
3   blue  cup   2.3

计算每种可能的颜色和商品组合的价格汇总统计数据的最简洁方法是什么?

预期输出例如:

colour     item      mean     stdev
red        cup       1.625    0.176
blue       jug       2.4      NA
blue       cup       2.3      NA

【问题讨论】:

    标签: python pandas statistics


    【解决方案1】:

    注意您创建数据框的方式强制列价格不再是数字字符串,因为numpy array 只接受一个dtype

    运行:

    df.price=pd.to_numeric(df.price)
    

    我将在groupby 之后使用describe

    df.groupby(['colour','item']).price.describe()# you can add reset_index() here
                 count   mean       std  min     25%    50%     75%   max
    colour item                                                          
    blue   cup     1.0  2.300       NaN  2.3  2.3000  2.300  2.3000  2.30
           jug     1.0  2.400       NaN  2.4  2.4000  2.400  2.4000  2.40
    red    cup     2.0  1.625  0.176777  1.5  1.5625  1.625  1.6875  1.75
    

    或者你可以使用agg

    df.groupby(['colour','item']).price.agg(['std','mean'])
    

    【讨论】:

    • 有没有办法让“颜色”和“项目”作为列标题与问题示例中的摘要统计列名称对齐?
    • reset_index() 照你说的做。
    【解决方案2】:

    您可以将groupby.agg 结合使用,并将meanstd 函数传递给它:

    print(df.groupby(['colour', 'item']).agg({'price':['mean', 'std']}).reset_index())
    
      colour item  price          
                    mean       std
    0   blue  cup  2.300       NaN
    1   blue  jug  2.400       NaN
    2    red  cup  1.625  0.176777
    

    【讨论】:

      猜你喜欢
      • 2014-04-09
      • 1970-01-01
      • 2019-03-19
      • 2018-08-11
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 2023-02-21
      相关资源
      最近更新 更多