StatsScared
StatsScared

Reputation: 537

Pandas: Groupby count as column value

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.

Upvotes: 2

Views: 95

Answers (2)

Wasif
Wasif

Reputation: 15470

Try .value_counts with .map

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

Upvotes: 1

Andy L.
Andy L.

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

Related Questions