如何替换"object"列中的 nan 值?



我如何在列中替换nan值,这是一个'对象',包含其他str并确保它进入主df而不仅仅是切片。

我已经试过了

covid_19_df.Country_code.fillna('OT')

但仍为空

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

我想让它看起来像这样

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

fillna默认不替换inplace,必须保存操作:

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

如果您有空字符串代替NaN,您可以通过pd.NA:

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

输出:

>>> covid_19_df
Country_code Country
0           OM    Oman
1           OM    Oman
2           OT   Other
3           OT   Other
4           OT   Other

最新更新