Reputation: 2155
I've got a dataframe and I want to say if value is equal or like, then call column "output" a new value.
My code is below
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'
Is there a way I can do this in a dictionary and loop?
for example
dict={Intercept : 1Base,
,'Xmas|Bank|Easter : 3Holiday
and so on
and then loop through this?
Upvotes: 0
Views: 498
Reputation: 1286
You can put your strings into a dict
d = {'^Intercept$': '1Base'
'Xmas|Bank|Easter': '3Holidays'
'BF': '9Events'
r'(?=.*Brand)(?=.*ME2)'): 'hjhjha'
r'(?=.*Trading)(?=.*ME2)'): 'ghghg'
r'(?=.*Sky)(?=.*PovRSP)'): 'dfdfdf'}
an iterate through this
for key, value in d.items():
df.loc[df['Varname'].str.contains(key), 'Output'] = value
Upvotes: 3