Reputation: 353
I have a dictionary that looks like this
dict = {'b' : '5', 'c' : '4'}
My dataframe looks something like this
A B
0 a 2
1 b NaN
2 c NaN
Is there a way to fill in the NaN values using the dictionary mapping from columns A to B while keeping the rest of the column values?
Upvotes: 25
Views: 24863
Reputation: 2544
Unfortunately, this isn't one of the options for a built-in function like pd.fillna()
.
Edit: Thanks for the correction. Apparently this is possible as illustrated in @Vaishali's answer.
However, you can subset the data frame first on the missing values and then apply the map with your dictionary.
df.loc[df['B'].isnull(), 'B'] = df['A'].map(dict)
Upvotes: 3
Reputation: 71
This can be done simply
df['B'] = df['B'].fillna(df['A'].apply(lambda x: dict.get(x)))
This can work effectively for a bigger dataset as well.
Upvotes: 7
Reputation: 38415
You can map dict values inside fillna
df.B = df.B.fillna(df.A.map(dict))
print(df)
A B
0 a 2
1 b 5
2 c 4
Upvotes: 42