python - 迭代数据框并根据条件替换值

标签 python pandas loops for-loop if-statement

我是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)

谢谢!

最佳答案

在pandas中最好避免循环,因为慢,所以使用numpy.where通过 Series.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'])

关于python - 迭代数据框并根据条件替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54684480/

相关文章:

python - 有人可以解释 Gtk2 包装吗?

python - 迭代 DataFrame 分类列以创建子图

python - 如何使用 pandas 的字符串索引将一列拆分为多列?

java - Android for循环等待点击事件计数器然后继续循环

Python - 另一个编码问题。 Windows 8.1,都是最新的 python。 pip 抛出异常

python - 如何制作windows的数据框?

linux - 如何在 Bash 中编写将在 CTRL+C 上中断的循环?

javascript - 在 JavaScript 中使用标签是不好的做法吗?

python - Django 用空值注释字段

Python:过滤掉两个pandas数据帧的相同列