Reputation: 537
I have a pandas dataframe that looks like this:
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:
Any tips would be helpful.
Upvotes: 2
Views: 95
Reputation: 15470
Try .value_counts
with .map
df['x_count'] = df['id'].map(df.value_counts('id'))
Upvotes: 1
Reputation: 25239
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')
Upvotes: 2