使用Pandas获得按年份和月份分组的独特用户数

2024-04-19 21:17:15 发布

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

我有这样一个数据帧:

|User|Month|Year|
| 1  | 3   |2010|
| 1  | 4   |2010|
| 2  | 4   |2010|
| 3  | 5   |2010|
| 7  | 8   |2011|
| 3  | 5   |2011|

我只想根据月份和年份得到不同的用户数

对于示例表

2010 3.month has 1 user (user 1)
2010 4.month has 1 user (user 2) (not user 1 because its already registered in 3. month)
2010 5. month has 1 user (user 3)

Tags: 数据示例notyearitshas年份月份
1条回答
网友
1楼 · 发布于 2024-04-19 21:17:15

下面是我将如何解决它。 1.取每个用户的第一个匹配项 2.Groupby以获取唯一计数

df.groupby('User').first().reset_index().groupby(['Year', 'Month'])['User'].nunique()

出[98]:

 Year  Month
 2010  3        1
       4        1
       5        1
 2011  8        1
 Name: User, dtype: int64

相关问题 更多 >