尝试替换我的数据框中列为“nan”的值(注意,不是“NaN”)
我读入了一个 excel 文件,然后尝试像这样替换 nan 值:
All_items_df = ALL_df[df_items].fillna(' ')
最后我得到一个仍然包含'nan'的输出
All_items_df ['Colour'].head(10)
Out[]:
7 nan
8 nan
9 nan
10 nan
13 nan
14 nan
15 nan
16 nan
18 nan
19 nan
Name: Colour, dtype: object
使用 isna() 或 isnull().value.all() 检查 nan 值,上述值的结果为 False。为什么它不能识别为 nan/na 值?
All_items_df ['Colour'].isnull().head(10)
Out[123]:
7 False
8 False
9 False
10 False
13 False
14 False
15 False
16 False
18 False
19 False
Name: Minor Feats, dtype: bool
然后我写入一个 csv 文件并将“nan”写入文件,即使指定不写出 nan
All_items_df.to_csv(folderpath + "All_items.csv",encoding="UTF-8", index=False, na_rep='')
请您参考如下方法:
您的 nan 看起来是字符串,实际上不是空值。在继续您计划进行的任何计算之前,您可以使用此代码将 nan 替换为实际的空值:
import numpy as np
df.Colour.replace('nan', np.nan, inplace=True)
示例:
>>> df
Colour
0 nan
1 nan
2 nan
3 Blue
4 nan
df.Colour.replace('nan', np.nan, inplace=True)
df.fillna('', inplace=True)
>>> df
Colour
0
1
2
3 Blue
4
