簡體   English   中英

如何在groupby的所有單個列中獲取唯一值的計數導致python pandas

[英]How to get count of unique values in all individual columns of a groupby result in 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”)]結果的唯一元素數。

您可以將groupby.aggnunique groupby.agg使用:

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

您可以對每個系列使用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

我希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM