然后将总和除以唯一计数

2024-06-26 14:28:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个df,看起来像这样:

test = pd.DataFrame({'date': ['1/07/2019', '1/08/2019', '1/08/2019','1/07/2019', '1/08/2019', '1/09/2019', '1/07/2019', '1/07/2019'],
                     'basket_id': ['AB789', 'CD674', 'KL237', 'AB789', 'CD674', 'RS234', 'ST089', 'OP448'],
                     'product_id': ['1839', '0368', '5360', '2524', '1036', '1184', '9280', '7721'],
                   'revenue': [400, 500, 350, 200, 100, 450, 50, 150]})
print(test)

现在,我想创建一个名为temp_test的df,它显示日期、收入总和、唯一篮子ID的计数,最后是每个篮子的平均收入列

temp_test = test.groupby(['date']).agg({'revenue': sum, 'basket_id': 'nunique'}).reset_index()
temp_test['rev_per_basket'] = test['revenue'] / test.groupby(['date'])['basket_id'].nunique()
print(temp_test)

然而,我的rev_per_basket专栏只显示NaN。理想情况下,它应该显示226.66、475和450。你知道哪里出了问题吗?谢谢


Tags: testiddfdaterevtempprintgroupby