我正在执行以下操作:
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})
但我想这样做groupby
连续具有多个值,例如 x<=7
, x<=9
, x<=11
等percentage
功能。
除了编写多个函数并调用它们之外,最简单的方法是什么?
所以基本上我想避免做这样的事情:
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.
最佳答案
您可以重写您的函数 - 创建由 bool 掩码填充的新列,然后使用 Series.mul
聚合 mean
和最后一个倍数 100
:
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
关于python - 更改 pandas groupby 使用的函数中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54648867/