简体   繁体   English

熊猫-创建一个新列,并在另一列中填充观察值

[英]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.

相关问题 熊猫-根据另一列的行总数创建新列的正确方法(试图在副本上设置的值)? - 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 如何从观察值创建新列并从另一列聚合值 - In pandas how to create new column from observations and aggregate values from another column Pandas-将列除以另一列,条件是值是否大于0? - Pandas- Dividing a column by another column conditional on if values are greater than 0? Pandas-如何获取另一列中每个对应值的行数 - Pandas- How to get number of times row occurs for each corresponding value in another column dataframe 清理:从 pandas- 的列中删除特定数量的零 - dataframe cleaning: removing a specific number of zeros from a column in pandas- Pandas-创建一个基于列值插入新行的表? - Pandas- creating a table that inserts new rows based on column values? pandas-列中每个唯一字符串/组的新计算行 - pandas- new calculated row for each unique string/group in a column 熊猫-如何将数据帧的转置作为列标题附加到另一个数据帧? - Pandas- How to append a transpose of dataframe to another dataframe as column headers? 基于 Pandas 中的另一列创建新列 - Create new column on basis of another column in Pandas Pandas:按列中的观察数量扩展DataFrame - Pandas: expanding DataFrame by number of observations in column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM