pandas ValueError:无法将字符串转换为浮点数:'4,6'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51479899/
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
ValueError: could not convert string to float: '4,6'
提问by mohamoud wueza
While reading from csv I have ValueError: could not convert string to float
. It begins from readng the file, after I give names to columns and remove NaNs.
从 csv 读取时,我有ValueError: could not convert string to float
. 它从读取文件开始,在我为列命名并删除 NaN 之后。
from pandas import read_csv
df = read_csv("propositio/data.csv", header=None,
sep=';', decimal=',')
cols = ['col1', 'col2', 'col3', 'col4']
df.columns = cols
df.dropna(inplace=True)
Here comes an error. I want to convert non-null object
into floats:
这里出现了一个错误。我想转换non-null object
成浮点数:
df = df.astype(float)
ValueError: could not convert string to float: '4,6'
ValueError:无法将字符串转换为浮点数:'4,6'
How can I fix it?
我该如何解决?
回答by Rakesh
Use str.replace
to replace comma with dot
用于str.replace
用点代替逗号
Ex:
前任:
import pandas as pd
df = pd.DataFrame({"A": ['4,6', "5.6", '6,6']})
df = df["A"].str.replace(',', ".").astype(float)
print(df)
Output:
输出:
0 4.6
1 5.6
2 6.6
Name: A, dtype: float64