How can I replace a nan value in an "object" column?

Question:

How can I replace a nan value in a column which is an ‘object’, contains other str and ensure it goes into the main df and not just the slice.

I have tried this

covid_19_df.Country_code.fillna('OT')

but it is still empty

 D    Country_code    Country   
 1.   OM              Oman  
 2.   OM              Oman  
 3.                   Other
 4.                   Other 
 5.                   Other 

I want it to look like this

 D    Country_code    Country   
 1.   OM              Oman  
 2.   OM              Oman  
 3.   OT              Other
 4.   OT              Other 
 5.   OT              Other 
Asked By: Nuro

||

Answers:

fillna does not replace inplace by default, you have to save the operation:

covid_19_df.Country_code = covid_19_df.Country_code.fillna('OT')

If you have empty strings instead NaN, you can replace them by pd.NA:

covid_19_df.Country_code = covid_19_df.Country_code.replace('', pd.NA).fillna('OT')

Output:

>>> covid_19_df
  Country_code Country
0           OM    Oman
1           OM    Oman
2           OT   Other
3           OT   Other
4           OT   Other
Answered By: Corralien
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.