我找不到与我有关的任何其他问题。如果我错过了,请帮我一个链接...
我有一个csv文件,如下所示:
"concentration"
"5"
"5"
"5"
"5"
"5"
"nan"
"nan"
"nan"
"nan"
"nan"
如果我用pandas read_csv阅读它," nan"值自动解释为NaN。但我想把它们作为一个字符串。应该是NaN的缺失值在第7行(实际上没有写任何内容)。
我试着这样读:
df = pd.read_csv(path, dtype= {'concentration': 'string'}, quoting = csv.QUOTE_NONNUMERIC, sep=',')
有人可以帮忙吗?
答案 0 :(得分:4)
您似乎可以使用keep_default_na
和na_values
。来自docs:
na_values : list-like or dict, default None
Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values
keep_default_na : bool, default True
If na_values are specified and keep_default_na is False the default NaN values are overridden, otherwise they’re appended to
所以这是代码
pd.read_csv('c:\\temp\\temp.txt', keep_default_na=False, na_values=[''])
concentration
0 5
1 5
2 5
3 5
4 5
5 NaN
6 nan
7 nan
8 nan
9 nan
10 nan