如何计算groupby的所有单独列中的唯一值的计数导致python pandas

时间:2016-12-02 12:23:29

标签: python pandas

我正在使用Pandas数据帧,并希望在数据帧的2列上获取groupby输出的各列中的唯一值计数。

我的输入数据框是:

id  number  name    time    method  level
121 567     XYZ     24      run     150
234 679     ABC     56      floor   120
121 567     XYZ     26      walk    150
578 865     EFG     89      fly     430
965 685     MNO     40      cry     278
578 865     MNO     67      fly     430

必需的输出

id  number  name    time    method  level
121 567     1       2       2       1
234 679     1       1       1       1
578 865     2       2       1       1
965 685     1       1       1       1

所以,我在输出中想要的是每个groupby([“id”,“number”)]结果的唯一元素数。

2 个答案:

答案 0 :(得分:3)

您可以将groupby.aggnunique

一起使用
df.groupby(['id', 'number']).agg(pd.Series.nunique)
Out: 
            name  time  method  level
id  number                           
121 567        1     2       2      1
234 679        1     1       1      1
578 865        2     2       1      1
965 685        1     1       1      1

答案 1 :(得分:1)

您可以在每个系列中使用groupby-apply然后使用apply来计算唯一值:

df.groupby(['id','number'])['name', 'time', 'method', 'level']\
    .apply(lambda x: x.apply(lambda y: y.drop_duplicates().count()))\
    .reset_index([0,1])

# Output:

    id  number  name  time  method  level
0  121     567     1     2       2      1
1  234     679     1     1       1      1
2  578     865     2     2       1      1
3  965     685     1     1       1      1

我希望这会有所帮助。