Pandas:获取具有多个对应值的所有ID

2024-06-02 06:26:26 发布

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

从如下所示的数据帧开始:

userId | preference
1      | coffee
2      | cake 
2      | tea
3      | tea
3      | tea
3      | tea
4      | apple
4      | tea

我需要将上述内容转换为:

userId | preference
2      | cake 
2      | tea
4      | apple
4      | tea

注意:用户标识1和用户标识3被删除,因为它们只有一个唯一的首选项。我只希望保留具有2个或更多唯一首选项的用户标识。我一直被困在这个问题上。尝试使用.grouby,但没有结果


Tags: 数据用户内容apple标识coffeecakeuserid
2条回答

获取每个用户标识的唯一值计数,如果大于1,则保留,否则放弃

df.loc[df.groupby('userId').preference.transform('nunique').gt(1)]
Out[26]: 
   userId preference
1       2       cake
2       2        tea
6       4      apple
7       4        tea

分组筛选似乎也适用于您的案例

df.groupby('userId').filter(lambda x: x['preference'].nunique()>1)

输出:

userId  |   preference
1   2   |   cake
2   2   |   tea
6   4   |   apple
7   4   |   tea

相关问题 更多 >