编程语言
首页 > 编程语言> > python-更改pandas groupby使用的函数中的值

python-更改pandas groupby使用的函数中的值

作者:互联网

我正在执行以下操作:

def percentage(x):
    return x[(x<=5)].count() / x.count() * 100

full_data = full_data.groupby(['Id', 'Week_id'], as_index=False).agg({'Volume': percentage})

但是我想用百分比函数中的x <= 7,x <= 9,x <= 11等多个值连续进行分组. 代替编写多个函数并调用它们的最简单方法是什么? 所以基本上我想避免做这样的事情:

def percentage_1(x):
    return x[(x<=5)].count() / x.count() * 100

full_data_1 = full_data.groupby(['Id', 'Week_id'], as_index=False).agg({'Volume': percentage_1})

def percentage_2(x):
    return x[(x<=7)].count() / x.count() * 100

full_data_2 = full_data.groupby(['Id', 'Week_id'], as_index=False).agg({'Volume': percentage_2})

# etc.

解决方法:

您可以重写函数-创建由布尔掩码填充的新列,然后将平均值和最后的100乘以Series.mul进行聚合:

n = 3

full_data['new'] = full_data['Volume'] <= n
full_data = full_data.groupby(['Id', 'Week_id'])['new'].mean().mul(100).reset_index()

功能解决方案:

def per(df, n):
    df['new'] = df['Volume'] <= n
    return df.groupby(['Id', 'Week_id'])['new'].mean().mul(100).reset_index()

编辑:从github开始的解决方案:

full_data = pd.DataFrame({
        'Id':list('XXYYZZXYZX'),
         'Volume':[2,4,8,1,2,5,8,2,6,4],
         'Week_id':list('aaabbbabac')
})

print (full_data)

val = 5
def per(c):
    def f1(x):
        return x[(x<=c)].count() / x.count() * 100
    return f1

full_data2 = full_data.groupby(['Id', 'Week_id']).agg({'Volume': per(val)}).reset_index()
print (full_data2)
  Id Week_id      Volume
0  X       a   66.666667
1  X       c  100.000000
2  Y       a    0.000000
3  Y       b  100.000000
4  Z       a    0.000000
5  Z       b  100.000000
def percentage(x):
    return x[(x<=val)].count() / x.count() * 100

full_data1 = full_data.groupby(['Id', 'Week_id'], as_index=False).agg({'Volume': percentage})

print (full_data1)
  Id Week_id      Volume
0  X       a   66.666667
1  X       c  100.000000
2  Y       a    0.000000
3  Y       b  100.000000
4  Z       a    0.000000
5  Z       b  100.000000

标签:pandas-groupby,pandas,python
来源: https://codeday.me/bug/20191108/2006607.html