Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个 DataFrame 对象df。中的列值之一df是ID 有许多具有相同 ID 的行。
df
ID
我想创建一个新列num_totals来计算每个 ID 的观察次数。例如,像这样:
num_totals
ID | Num Totals 1 | 3 1 | 3 1 | 3 2 | 2 2 | 2 3 | 3 3 | 3 3 | 3 4 | 1
在 Pandas 中最快的方法是什么?
A simple groupby+transform would work:
df['num_totals'] = df.groupby('ID').transform('count')