我有一个数据框,我想说值是否相等或相似,然后将列“输出”称为新值。
我的代码在下面
df.loc[df['Varname']=='Intercept','Output']='1Base'
df.loc[df['Varname'].str.contains('Xmas|Bank|Easter'),'Output']='3Holidays'
df.loc[df['Varname'].str.contains('BF'),'Output']='9Events'
df.loc[df['Varname'].str.contains(r'(?=.*Brand)(?=.*ME2)'),'Output']='hjhjha'
df.loc[df['Varname'].str.contains(r'(?=.*Trading)(?=.*ME2)'),'Output']='ghghg'
df.loc[df['Varname'].str.contains(r'(?=.*Sky)(?=.*PovRSP)'),'Output']='dfdfdf'
有没有办法在字典和循环中做到这一点?
例如
dict={Intercept : 1Base,
,'Xmas|Bank|Easter : 3Holiday
以此类推
然后循环浏览?
答案 0 :(得分:2)
您可以将字符串放入字典中
d = {'^Intercept$': '1Base'
'Xmas|Bank|Easter': '3Holidays'
'BF': '9Events'
r'(?=.*Brand)(?=.*ME2)'): 'hjhjha'
r'(?=.*Trading)(?=.*ME2)'): 'ghghg'
r'(?=.*Sky)(?=.*PovRSP)'): 'dfdfdf'}
对此进行迭代
for key, value in d.items():
df.loc[df['Varname'].str.contains(key), 'Output'] = value