将字符串转换为浮点 pandas [英] Convert string to float pandas
本文介绍了将字符串转换为浮点 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一个简单的问题:我有一个从csv文件导入的数据集,其中包含带有数字值的字符串列.逗号后是小数位.
Simple question: I have a dataset, imported from a csv file, containing a string column with numeric values. After the comma are decimal places.
我想转换为浮点数.基本上就是这样:
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?
先谢谢了.
推荐答案
If want specify columns for converting:
cols = ['col1','col2']
df[cols] = df[cols].replace(',','.', regex=True).astype(float)
另一种解决方案是在 read_csv
中使用参数decimal=','
,然后正确地将列解析为浮点数:
Another solution is use parameter decimal=','
in read_csv
, then columns are correctly parsed to floats:
df = pd.read_csv(file, decimal=',')
这篇关于将字符串转换为浮点 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文