pandas -创建一个新列,并在另一列中填充观察值 [英] Pandas- Create a new column filled with the number of observations in another column
本文介绍了 pandas -创建一个新列,并在另一列中填充观察值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个DataFrame对象df
. df
中的列值之一是ID
.许多行具有相同的ID.
I have a DataFrame object df
. One of the column values in df
is ID
There are many rows with the same ID.
我想创建一个新列num_totals
,该列计算每个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
在Pandas中最快的方法是什么?
What's the fastest way to do this in Pandas?
推荐答案
一个简单的groupby + transform将起作用:
A simple groupby+transform would work:
df['num_totals'] = df.groupby('ID').transform('count')
这篇关于 pandas -创建一个新列,并在另一列中填充观察值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文