Skip to main content
 首页 » 编程设计

python之按年-周分组的 Pandas 唯一用户数

2024年10月24日12myhome

我有一个 report_date 列,我想按年-周汇总并计算唯一用户的数量。

import pandas as pd 
from io import StringIO 
 
datastring = StringIO("""\ 
report_date  user_id 
2015-12-01         1 
2015-12-01         2 
2015-12-01         2 
2015-12-02         2 
2015-12-02         3 
2016-01-01         1 
""") 
 
df = pd.read_table(datastring, sep='\s\s+', engine='python') 
df['report_date'] = pd.to_datetime(df['report_date']) 

我想要的输出:

2015-48    3 
2016-00    1 

我想出了一个解决方案(在下面发布)但是当使用更大的数据集(> 1MM 行)时它相对较慢。好奇这个问题是否有更好的解决方案。

请您参考如下方法:

由于您的列已经是日期时间,因此无需在字符串上转换为字符串和 groupby,我们可以在 year and week 上分组组件,然后调用 nunique :

In [108]: 
df.groupby([df['report_date'].dt.year, df['report_date'].dt.week])['user_id'].nunique() 
 
Out[108]: 
report_date  report_date 
2015         49             3 
2016         53             1 
Name: user_id, dtype: int64