[英]Show unique count of specific values in column, groupby an additional column using pandas
I have a dataset, df, where I would like to group by one column, reveal the counts of each unique value and display the proper column.我有一个数据集 df,我想按一列分组,显示每个唯一值的计数并显示正确的列。
data数据
Id location
e-db ny
e-db ny
e-db ny
f-a ny
f-a ny
gr-x ca
desired想要的
Id location count
e-db ny 3
f-a ny 2
gr-x ca 1
doing正在做
df.groupby('location')['Id'].nunique()
However, this is not showing me the unique Id's and the actual value.但是,这并没有向我显示唯一 ID 和实际值。 Any suggestion is appreciated任何建议表示赞赏
You can also do this:你也可以这样做:
df2 = pd.DataFrame()
df2['location'] = df.groupby('Id')['location'].nth(0)
df2['count'] = df.groupby('Id').count()
Output: Output:
Id location count
e-db ny 3
f-a ny 2
gr-x ca 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.