[英]Show unique count of specific values in column, groupby an additional column using pandas
我有一個數據集 df,我想按一列分組,顯示每個唯一值的計數並顯示正確的列。
數據
Id location
e-db ny
e-db ny
e-db ny
f-a ny
f-a ny
gr-x ca
想要的
Id location count
e-db ny 3
f-a ny 2
gr-x ca 1
正在做
df.groupby('location')['Id'].nunique()
但是,這並沒有向我顯示唯一 ID 和實際值。 任何建議表示贊賞
你也可以這樣做:
df2 = pd.DataFrame()
df2['location'] = df.groupby('Id')['location'].nth(0)
df2['count'] = df.groupby('Id').count()
Output:
Id location count
e-db ny 3
f-a ny 2
gr-x ca 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.