【问题标题】:Iterating over a data frame and replacing value depending on a condition迭代数据框并根据条件替换值
【发布时间】:2019-07-08 03:07:36
【问题描述】:

我是 python 新手(来自 R),我不知道如何在 python 中迭代数据框。我在下面提供了一个数据框和一个可能的“干预”列表。我试图做的是搜索数据框中的“干预”列,如果干预在“intervention_list”中,则将值替换为“是干预”,但如果“NaN”替换为“无干预”。

任何指导或帮助将不胜感激。

import pandas as pd
intervention_list = ['Intervention 1', 'Intervention 2']
df = pd.DataFrame({'ID':[100,200,300,400,500,600,700],
                  'Intervention':['Intervention 1', 'NaN','NaN','NaN','Intervention 2','Intervention 1','NaN']})
print(df)

我希望完成的数据框如下所示:

df_new = pd.DataFrame({'ID':[100,200,300,400,500,600,700],
                  'Intervention':['Yes Intervention', 'No Intervention','No Intervention','No Intervention','Yes Intervention','Yes Intervention','No Intervention']})
print(df_new)

谢谢!

【问题讨论】:

    标签: python pandas loops for-loop if-statement


    【解决方案1】:

    在 pandas 中最好避免循环,因为速度慢,所以使用 numpy.whereSeries.isna 测试缺失值或 Series.notna 用于矢量化解决方案:

    df['Intervention'] = np.where(df['Intervention'].isna(),'No Intervention','Yes Intervention')
    

    或者:

    df['Intervention'] = np.where(df['Intervention'].notna(),'Yes Intervention','No Intervention')
    

    如果NaN 是字符串,则通过==Series.eq 进行测试:

    df['Intervention']=np.where(df['Intervention'].eq('NaN'),'No Intervention','Yes Intervention')
    

    但如果还需要在列表中进行测试,请使用numpy.select:

    m1 = df['Intervention'].isin(intervention_list)
    m2 = df['Intervention'].isna()
    
    #if not match m1 or m2 create default None
    df['Intervention'] = np.select([m1, m2],
                                  ['Yes Intervention','No Intervention'],
                                  default=None)
    

    #if not match m1 or m2 set original value column Intervention
    df['Intervention'] = np.select([m1, m2],
                                  ['Yes Intervention','No Intervention'],
                                  default=df['Intervention'])
    

    【讨论】:

    • @Jake - 刚刚意识到还需要测试intervention_list,检查编辑的答案。
    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多