Pandas: Groupby count as column value

Viewed 77

I have a pandas dataframe that looks like this:

enter image description here

I would like to generate counts instances of 'x' (regardless of whether they're unique, or not) per 'id'. The result would be insert as a column labeled 'x_count' as shown below:

enter image description here

Any tips would be helpful.

2 Answers

Simply a groupby with transform count

df['x_count'] = df.groupby('id')['x'].transform('count')

If you also want to count the NaN, use `size'

df['x_count'] = df.groupby('id')['x'].transform('size')

Try .value_counts with .map

df['x_count'] = df['id'].map(df.value_counts('id'))
Related