我有这段代码可以在python3中正常工作。
resumen = datos.groupby(['subid2']).agg(
total_clicks = pd.NamedAgg('clicks', 'sum'),
total_revenue = pd.NamedAgg('revenue', 'sum')
)
resumen['avg_cpc'] = resumen['total_revenue'] / resumen['total_clicks']
print(resumen)
words = datos.groupby(['subid2','keyword']).agg(
total_clicks = pd.NamedAgg('clicks', 'sum'),
total_revenue = pd.NamedAgg('revenue', 'sum')
)
words['avg_cpc'] = words['total_revenue'] / words['total_clicks']
print(words)
如您所见,#2与#1几乎完全相同,只是在groupby上添加了一个元素。
我尝试将#2更改为:
words = resumen.groupby('keyword'])
print(words)
认为我可以保存一些代码行。有可能这样做吗?
谢谢
答案 0 :(得分:0)
您将编写一个带有灵活参数的函数(给它一个描述性名称,与下面的不同):by
遵循与groupby
中的参数相同的限制。
def my_func(df, by):
res = df.groupby(by).agg(
total_clicks = pd.NamedAgg('clicks', 'sum'),
total_revenue = pd.NamedAgg('revenue', 'sum')
)
res['avg_cpc'] = res['total_revenue'] / res['total_clicks']
return res
然后
print(my_func(datos, 'subid2'))
print(my_func(datos, ['subid2', 'keyword']))