[英]Pandas- Create a new column filled with the number of observations in another column
I have a DataFrame object df
. 我有一个DataFrame对象df
。 One of the column values in df
is ID
There are many rows with the same ID. df
中的列值之一是ID
有许多行具有相同的ID。
I want to create a new columns num_totals
that counts the number of observation for each ID. 我想创建一个新的列num_totals
,用于计数每个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? 在Pandas中最快的方法是什么?
一个简单的groupby + transform将起作用:
df['num_totals'] = df.groupby('ID').transform('count')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.