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

Time:01-23

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 

CodePudding user response:

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
  • Related