关于python:ValueError:无法将字符串转换为float:’4,6′

ValueError: could not convert string to float: '4,6'

从csv读取时,我有ValueError: could not convert string to float。 在我给列命名并删除NaN之后,它从读取文件开始。

1
2
3
4
5
6
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)

这是一个错误。 我想将non-null object转换为浮点数:

1
df = df.astype(float)

ValueError: could not convert string to float: '4,6'

我该如何解决?


使用str.replace用点替换逗号

例如:

1
2
3
4
5
import pandas as pd

df = pd.DataFrame({"A": ['4,6',"5.6", '6,6']})
df = df["A"].str.replace(',',".").astype(float)
print(df)

输出:

1
2
3
4
0    4.6
1    5.6
2    6.6
Name: A, dtype: float64