![](/img/trans.png)
[英]Pandas- correct way to create a new column based on the sum of rows of another column (value trying to be set on a copy)?
[英]Pandas- Create a new column filled with the number of observations in another column
我有一个DataFrame对象df
。 df
中的列值之一是ID
有许多行具有相同的ID。
我想创建一个新的列num_totals
,用于计数每个ID的观察次数。 例如,如下所示:
ID | Num Totals
1 | 3
1 | 3
1 | 3
2 | 2
2 | 2
3 | 3
3 | 3
3 | 3
4 | 1
在Pandas中最快的方法是什么?
一个简单的groupby + transform将起作用:
df['num_totals'] = df.groupby('ID').transform('count')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.