代码之家  ›  专栏  ›  技术社区  ›  Yog

使用python pandas上的条件计算两列上的平均值Group by。只打印每个类别的平均值?

  •  1
  • Yog  · 技术社区  · 7 年前

    输入

    Fruit Count Price tag
    Apple  55    35   red
    Orange 60    40   orange
    Apple  60    36   red
    Apple  70    41   red
    

    产出1

    Fruit Mean  tag
    Apple 35.5  red
    Orange 40   orange
    

    我需要 意思是 条件价格在31到40之间

    产出2

        Fruit   Count  tag
        Apple   2   red
        Orange  1   orange
    

    我需要 计数 条件价格在31到40之间

    请帮忙

    1 回复  |  直到 7 年前
        1
  •  1
  •   jezrael    7 年前

    使用 between 具有 boolean indexing 用于筛选:

    df1 = df[df['Price'].between(31, 40)]
    print (df1)
        Fruit  Count  Price     tag
    0   Apple     55     35     red
    1  Orange     60     40  orange
    2   Apple     60     36     red
    

    如果可能,按聚合函数显示多个列:

    df2 = df1.groupby(['Fruit', 'tag'])['Price'].agg(['mean','size']).reset_index()
    print (df2)
        Fruit     tag  mean  size
    0   Apple     red  35.5     2
    1  Orange  orange  40.0     1
    

    或2个单独的数据帧:

    df3 = df1.groupby(['Fruit', 'tag'], as_index=False)['Price'].mean()
    print (df3)
        Fruit     tag  Price
    0   Apple     red   35.5
    1  Orange  orange   40.0
    
    df4 = df1.groupby(['Fruit', 'tag'])['Price'].size().reset_index()
    print (df4)
        Fruit     tag  Price
    0   Apple     red      2
    1  Orange  orange      1