【问题标题】:How can i get a groupby 2 columns results into a new column如何将 groupby 2 列结果放入新列
【发布时间】:2023-02-03 00:45:23
【问题描述】:

我有一个看起来像这样的 df:

name url
timmy target.com
cosmo michaels.com
wanda macys.com
chester michaels.com
aj michaels.com
chester michaels.com

我想通过 url 计算每个 url 有多少个唯一名称,所以它会像这样: 即使 michaels.com 出现了 4 次,唯一名称计数也将为 3,因为 chester 被列出了两次。

name url unique_names
timmy target.com 1
cosmo michaels.com 3
wanda macys.com 1
chester michaels.com 3
aj michaels.com 3
chester michaels.com 3

这对它进行了正确的分组,但它没有给我在新专栏中想要的结果

df.groupby(['url','name']).count()

先感谢您!!

【问题讨论】:

  • 想想select count(distinct name), url from table group by url
  • 不幸的是,@Mike'Pomax'Kamermans 我不确定如何在 python 中做到这一点。

标签: python pandas group-by


【解决方案1】:

我认为你 pandas unique() 可以帮助你计算独特的数量。

df.groupby(['url','name']).unique().count()

【讨论】:

    猜你喜欢
    • 2022-08-11
    • 1970-01-01
    • 2017-11-14
    • 2023-02-03
    • 2019-04-12
    • 2017-08-19
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多