Natasha
Natasha

Reputation: 353

Pandas: fill in NaN values with dictionary references another column

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

Answers (3)

3novak
3novak

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

abburi
abburi

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

Vaishali
Vaishali

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

Related Questions