I have a DataFrame object df
. One of the column values in df
is ID
There are many rows with the same ID.
I want to create a new columns num_totals
that counts the number of observation for each ID. For example, something like this:
ID | Num Totals
1 | 3
1 | 3
1 | 3
2 | 2
2 | 2
3 | 3
3 | 3
3 | 3
4 | 1
What's the fastest way to do this in Pandas?
一个简单的groupby + transform将起作用:
df['num_totals'] = df.groupby('ID').transform('count')
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.