【问题标题】:Grouping by and filtering for an agg function聚合函数的分组和过滤
【发布时间】:2019-11-11 00:39:16
【问题描述】:

我正在尝试计算两列下的平均重量,性别和类型,因为 df 如下:

sex |  type     | weight
 M     Obese      305
 F     Normal     100
 M     Underweight 105

【问题讨论】:

    标签: python python-3.x pandas data-science


    【解决方案1】:

    您在这里使用了filter 错误。将您想要保留的内容传递给like 参数:

    df.groupby(['sex','type'])['weight'].mean().filter(like='Obese') 
    

    输出:

    sex  type 
    M    Obese    305
    Name: weight, dtype: int64
    

    【讨论】:

    • 如果只有两个,你可以过滤两次,即filter(like='Obese').filter(like='M')
    • 否则最好分两步完成。首先获取平均值,然后使用具有多个条件的布尔索引。
    【解决方案2】:

    你想这样做吗?

    import pandas as pd
    
    df = pd.DataFrame({'sex': ['M', 'F', 'M'], 'type':['obese', 'Normal' ,'Underweight'],
        'weight': [305, 100, 105]})
    print(df[df['type'] == 'obese']['weight'].mean())
    

    首先,我认为您不需要 filter() 函数,它所做的事情与您想象的不同。其次,您总是希望先选择或“过滤”,然后再进行计算。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 2020-12-24
      相关资源
      最近更新 更多