python-3.x - 如何计算每组中的记录数并将它们添加到主数据集中?

标签 python-3.x pandas

鉴于我有一个数据集如下:

import pandas as pd
import numpy as np

dt = {
    "facility":["Ann Arbor","Ann Arbor","Detriot","Detriot","Detriot"],
    "patient_ID":[4388,4388,9086,9086,9086],
    "year":[2004,2007,2007,2008,2011],
    "month":[8,9,9,6,2],
    "Nr_Small":[0,0,5,12,10],
    "Nr_Medium":[3,1,1,4,3],
    "Nr_Large":[2,0,0,0,0]
}

dt = pd.DataFrame(dt)
dt.head()

我需要添加一列来显示每组患者中的记录数。这就是我正在做的事情:

dt["NumberOfVisits"] = dt.groupby(['patient_ID']).size()

或者我尝试过这个:

但它在我的数据集中添加了一列 Nas。但是,我最喜欢的输出如下

enter image description here

最佳答案

在这里使用转换:

df["NumberOfVisits"]=df.groupby(['patient_ID'])['patient_ID'].transform('size')
print(df)

    facility  patient_ID  year  month  Nr_Small  Nr_Medium  Nr_Large  \
0  Ann Arbor        4388  2004      8         0          3         2   
1  Ann Arbor        4388  2007      9         0          1         0   
2    Detriot        9086  2007      9         5          1         0   
3    Detriot        9086  2008      6        12          4         0   
4    Detriot        9086  2011      2        10          3         0   

   NumberOfVisits  
0               2  
1               2  
2               3  
3               3  
4               3  

关于python-3.x - 如何计算每组中的记录数并将它们添加到主数据集中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59704970/

相关文章:

python - 具有局部变量的全局方法线程安全

python - 在 Pandas 中将一列拆分为多列

python - Pandas - 展平一列字典列表

python - 滚动窗口不包括当前行

python - 如何将 Pandas 系列装箱,将每个箱子的箱子大小设置为最大/最小预设值

python - 属性错误 : 'NoneType' object has no attribute 'format'

python-3.x - 如何仅使用discord.py 在 webhook 中发送嵌入内容

python-3.x - 无法捕获的空字节 csv.Error 异常

Python 从 csv 列表发送电子邮件

python - 基于索引的跨 2 个数据帧的函数 (python)