22

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?

Natasha
  • 323
  • 1
  • 2
  • 6

3 Answers3

38

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
Vaishali
  • 37,545
  • 5
  • 58
  • 86
6

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.

abburi
  • 61
  • 1
  • 2
2

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)
Vaishali
  • 37,545
  • 5
  • 58
  • 86
3novak
  • 2,506
  • 1
  • 17
  • 28