python数据帧替换和应用
当我尝试时:python数据帧替换和应用,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,当我尝试时: df['Value'] = df['Value'].str.replace(',', '.').replace(' ', '').astype(float) 它将抛出以下错误: ValueError: could not convert string to float: '-1 750.5' 但当我使用: df['Value'] = df['Value'].apply( lambda x: float(x.replace(',', '.').replace(' ', '
df['Value'] = df['Value'].str.replace(',', '.').replace(' ', '').astype(float)
它将抛出以下错误:
ValueError: could not convert string to float: '-1 750.5'
但当我使用:
df['Value'] = df['Value'].apply(
lambda x: float(x.replace(',', '.').replace(' ', '')))
这会奏效的。我在这里做错了什么?此处用于默认子字符串替换和非子字符串替换,因此可以将一个或多个空格替换为'
使用\s+
:
#added second str.replace
df['Value'] = df['Value'].str.replace(',', '.').str.replace('\s+', '').astype(float)
你错过了第二个str。
#added regex=True for substring replacement in Series.replace
df['Value'] = df['Value'].str.replace(',', '.').replace('\s+', '', regex=True).astype(float)
#added regex=True for substring replacement in Series.replace with dictionary
df['Value'] = df['Value'].replace({',': '.', '\s+': ''}, regex=True).astype(float)