简体   繁体   中英

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.

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. 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:

Id  location    count
e-db    ny       3
f-a     ny       2
gr-x    ca       1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM