如何将每个组的重复项放入数据框架中?

发布于 2025-02-07 15:44:50 字数 529 浏览 0 评论 0原文

我有以下数据集:

id1   id2     value
a1    b1     "main"
a1    b1     "main"
a1    b1     "secondary"
a2    b2     "main"
a2    b2     "repair"
a2    b2     "uploaded"
a2    b2     "main"

我想将重复值丢弃在value id1 和id2 group中。因此,所需的结果是:

id1   id2     value
a1    b1     "main"
a1    b1     "secondary"
a2    b2     "main"
a2    b2     "repair"
a2    b2     "uploaded"

我该怎么做?我知道方法drop_duplicates,但是如何使用groupby使用它?

I have the following dataset:

id1   id2     value
a1    b1     "main"
a1    b1     "main"
a1    b1     "secondary"
a2    b2     "main"
a2    b2     "repair"
a2    b2     "uploaded"
a2    b2     "main"

I want to drop duplicate values in the column called value in each id1 and id2 group. So the desired result is:

id1   id2     value
a1    b1     "main"
a1    b1     "secondary"
a2    b2     "main"
a2    b2     "repair"
a2    b2     "uploaded"

How could I do that? I know the method drop_duplicates, but how can I use it with groupby?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你不是我要的菜∠ 2025-02-14 15:44:50

尝试:

x = (
    df.groupby(["id1", "id2"])
    .apply(lambda x: x.drop_duplicates("value"))
    .reset_index(drop=True)
)
print(x)

打印:

  id1 id2        value
0  a1  b1       "main"
1  a1  b1  "secondary"
2  a2  b2       "main"
3  a2  b2     "repair"
4  a2  b2   "uploaded"

Try:

x = (
    df.groupby(["id1", "id2"])
    .apply(lambda x: x.drop_duplicates("value"))
    .reset_index(drop=True)
)
print(x)

Prints:

  id1 id2        value
0  a1  b1       "main"
1  a1  b1  "secondary"
2  a2  b2       "main"
3  a2  b2     "repair"
4  a2  b2   "uploaded"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文