pandas 将字符串转换为浮动熊猫
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46758620/
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
Convert string to float pandas
提问by SQL_M
Simple question: I have a dataset, imported from a csv file, containing a string column with numeric values. After the comma are decimal places.
简单的问题:我有一个从 csv 文件导入的数据集,其中包含一个带有数值的字符串列。逗号后面是小数位。
I want to convert to float. Basically,it's just this:
我想转换为浮动。基本上,就是这样:
x = ['27,10083']
df = pd.DataFrame(x)
df.astype(float)
Why does this not work and how to fix this simple issue?
为什么这不起作用以及如何解决这个简单的问题?
Thanks in advance.
提前致谢。
回答by jezrael
Assign output with replace
:
分配输出replace
:
df = df.replace(',','.', regex=True).astype(float)
If want specify columns for converting:
如果要指定要转换的列:
cols = ['col1','col2']
df[cols] = df[cols].replace(',','.', regex=True).astype(float)
Another solution is use parameter decimal=','
in read_csv
, then columns are correctly parsed to floats:
另一个解决方案是使用参数decimal=','
in read_csv
,然后将列正确解析为浮点数:
df = pd.read_csv(file, decimal=',')