简体   繁体   中英

Pandas: Groupby count as column value

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.

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'))

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