Pandas: populate NaN values ​​with dictionary links with another column

I have a dictionary that looks like

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 populate NaN values ​​using dictionary matching from columns A to B while keeping the rest of the column values?

+5
source share
3 answers

You can match the 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
+8
source

Unfortunately, this is not one of the options for a built-in function, such as pd.fillna().

Change: Thanks for the fix. Apparently this is possible, as shown in @Vaishali's answer.

However, you can first set the data subframe to missing values, and then apply the map with your dictionary.

df.loc[df['B'].isnull(), 'B'] = df['A'].map(dict)
+1

df['B'] = df['B'].fillna(df['A'].apply(lambda x: dict.get(x)))

.

+1

Source: https://habr.com/ru/post/1672522/


All Articles