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