【问题标题】:Count the occurrence of one column based on another根据另一列计算一列的出现次数
【发布时间】:2021-04-12 06:02:18
【问题描述】:

我有一个这样的数据框

System package
mac abc
mac bcd
windows bcd
mac abc

我想要一个 python 代码来获得这样的数据框

System count of distinct package
mac 2
windows 1

【问题讨论】:

  • 请发布您尝试过的部分代码并指出您卡在哪里。
  • 我试过了,但它没有给我想要的结果 result= df.groupby(['system','package'])['system'].count()
  • 检查建议的解决方案。请注意,我将列命名为“a”和“b”,因此您必须自己更改它。

标签: python group-by count multiple-columns distinct


【解决方案1】:

创建数据框:

pd.DataFrame(data={"a":["mac","mac","windows","mac",],"b": ["abc", "bcd", "bcd", "abc"]})

分组:

t.groupby('a').b.nunique()

输出:

    a
mac        2
windows    1
Name: b, dtype: int64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 2021-09-09
    • 2022-01-04
    • 2022-06-16
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多