Suppose I have df
:
df = pd.DataFrame({'col1': ['A', 'B', 'C', 'D', 'E']})
And d
:
d = {'A': 1, 'B': 2}
I want to create df['col2']
such that the values are fetched from d
if they exist there, and if not equalize them with some fill value (say, 3
). I can do this by:
df['col2'] = pd.Series(np.NaN)
for k, v in d.items():
df['col2'] = np.where(df['col1']==k, v, df['col2'])
df['col2'] = df.col2.fillna(3)
Which gives me:
df
col1 col2
0 A 1.0
1 B 2.0
2 C 3.0
3 D 3.0
4 E 3.0
My question is: is it possible to achieve this without using a loop like a do?