Shlomi Schwartz
Shlomi Schwartz

Reputation: 8913

Python Pandas - Replace NaN values using dict

With the following DF:

     A  B
0    a  1
1    b  2
2  NaN  1
3  NaN  2

I would like to replace NaN values of A based on the numeric representation of B, to get:

     A  B
0    a  1
1    b  2
2    a  1
3    b  2

I've built a dictionary of B/A values: {1 : 'a', 2: 'b'}

How can I apply the change to the NaN values?

Upvotes: 0

Views: 145

Answers (1)

jezrael
jezrael

Reputation: 863226

Use Series.fillna with Series.map:

d = {1 : 'a', 2: 'b'}
df.A = df.A.fillna(df.B.map(d))
print (df)
   A  B
0  a  1
1  b  2
2  a  1
3  b  2

I suggest use map because replace is slowier and if no match in map is returned missing value (like original) not value of B:

df["A"] = df["A"].fillna(df["B"].replace({1 : 'a', 2: 'b'}))
print (df)
   A  B
0  a  1
1  b  2
2  a  1
3  3  3 <- changed last value to 3

d = {1 : 'a', 2: 'b'}
df.A = df.A.fillna(df.B.map(d))
print (df)
     A  B
0    a  1
1    b  2
2    a  1
3  NaN  3

Upvotes: 5

Related Questions