gpt4 book ai didi

python - Pandas - 按 id 分组并删除重复项

转载 作者:太空宇宙 更新时间:2023-11-03 15:26:45 25 4
gpt4 key购买 nike

我有以下数据。

userid itemid timestamp
1 1 50
1 2 50
1 3 50
1 4 60
2 1 40
2 2 50

我想删除具有重复时间戳的用户。在上面的示例中,我想删除 userid=1,因为他在时间戳=50 时查看了多个项目。 userid=2 不应被删除,因为他查看了不同时间戳的项目。

谁能帮我吗?

最佳答案

选项 1
使用重复

dropid = df.loc[
df.duplicated(subset=['userid', 'timestamp']),
'userid'
].unique()
df[~df.userid.isin(dropid)]

选项 2
使用groupbyfilter

df.set_index(['userid', 'timestamp']).groupby(level=0).filter(
lambda x: ~x.index.is_unique
).reset_index()

关于python - Pandas - 按 id 分组并删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43082659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com