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.