【问题标题】:Loop through dataframe in python to select specific row循环遍历python中的数据框以选择特定行
【发布时间】:2021-12-31 07:36:17
【问题描述】:

我有 5864 名 ICU 患者时间序列数据,我的数据框是这样的。每行是各个患者在特定时间的 ICU 停留时间。

HR SBP DBP ICULOS Sepsis P_ID
92 120 80 1 0 0
98 115 85 2 0 0
93 125 75 3 1 0
95 130 90 4 1 0
102 120 80 1 0 1
109 115 75 2 0 1
94 135 100 3 0 1
97 100 70 4 1 1
85 120 80 5 1 1
88 115 75 6 1 1
93 125 85 1 0 2
78 130 90 2 0 2
115 140 110 3 0 2
102 120 80 4 0 2
98 140 110 5 1 2

我想根据患者 ID 选择脓毒症 = 1(仅限第一个小时)的 ICULOS。就像在 P_ID = 0 中一样,在 ICULOS = 3 处脓毒症 = 1。我使用代码对单个患者(只有单个患者的数据的数据框)执行了此操作:

x = df[df['Sepsis'] == 1]["ICULOS"].values[0]
print("ICULOS at which Sepsis Label = 1 is:", x)
# Output
ICULOS at which Sepsis Label = 1 is: 46

如果我想为每个 P_ID 检查它,我必须这样做 5864 次。有人可以使用循环帮助我编写代码吗?循环将转到每个 P_ID,然后给出脓毒症 = 1 的 ICULOS 结果。期待帮助。

【问题讨论】:

    标签: python pandas dataframe loops for-loop


    【解决方案1】:

    首先,过滤具有 Sepsis=1 的行。它会自动过滤没有脓毒症为 1 的 P_ID。因此,您将有更少的患者需要迭代。

    df1 = df[df.Sepsis==1]
    for pid in df.P_ID.unique():
        if pid not in df.P_ID:
            print("P_ID: {pid} - it has no iclus at Sepsis Lable = 1")
        else:
            iclus = df1[df1.P_ID==pid].ICULOS.values[0]
            print(f"P_ID: {pid} - ICULOS at which Sepsis Label = 1 is: {iclus}")
    
            
    
    

    【讨论】:

    • 感谢您的回答,但我想要所有患者,我将数据从 40k 患者缩减到约 6k 患者。
    • 检查编辑。您将为所有患者运行查询。如果患者没有脓毒症标签 = 1 的数据,它将执行 else 条件。
    • 感谢拉比巴的回答
    【解决方案2】:
    for x in df['P_ID'].unique():
    
       print(df.query('P_ID == @x and Sepsis == 1')['ICULOS'][0])
    
    

    【讨论】:

    • UndefinedVariableError: name 'x' is not defined
    • 已更正。立即尝试
    • 收到此错误KeyError: 0
    • print(df.query('P_ID == @x and Sepsis == 1')['ICULOS'].values[0]) 如果是这样的话
    • 数据框中是否有没有脓毒症 == 1 的患者?
    猜你喜欢
    • 2021-11-01
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多