pandas.read_csv 读取字符串而不是浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28624628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas.read_csv reading string instead of float
提问by Olivier
My program keeps reading the input file as a string, even though it all values are floats.
我的程序一直将输入文件作为字符串读取,即使它的所有值都是浮点数。
pd.read_csv('input.txt', sep=' ', dtype=np.float32)
Also, my array contains multiple dots in the float values for some reason, even though the format is fine in my text
此外,由于某种原因,我的数组在浮点值中包含多个点,即使我的文本格式很好
input.txt content:
input.txt 内容:
-0.90051 -0.90051 -1.071287 -1.098813 -1.023997 -0.90051 -1.187293
result of pd.read_csv('input.txt', sep=' ', dtype=np.float32)
pd.read_csv('input.txt', sep=' ', dtype=np.float32) 的结果
-0.90051, -0.90051.1, -1.071287, -1.098813, -1.023997, -0.90051.2 -1.187293,
回答by EdChum
You have not told read_csvthat you have no header line hence you're observing the additional decimal points as the names clash, pass header=Noneto read_csv:
您没有告诉read_csv您没有标题行,因此您在名称冲突时观察到额外的小数点,传递header=None给read_csv:
In [354]:
# your code
temp='''-0.90051 -0.90051 -1.071287 -1.098813 -1.023997 -0.90051 -1.187293'''
pd.read_csv(io.StringIO(temp), sep=' ', dtype=np.float32)
Out[354]:
Empty DataFrame
Columns: [-0.90051, -0.90051.1, -1.071287, -1.098813, -1.023997, -0.90051.2, -1.187293]
Index: []
In [355]:
# pass header=None
pd.read_csv(io.StringIO(temp), sep=' ', header=None, dtype=np.float32)
Out[355]:
0 1 2 3 4 5 6
0 -0.90051 -0.90051 -1.071287 -1.098813 -1.023997 -0.90051 -1.187293

