![](/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.