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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:57:54  来源:igfitidea点击:

pandas.read_csv reading string instead of float

pythonnumpypandas

提问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=Noneread_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