Когда я пытаюсь:
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(' ', '')))
Это сработает. Что я здесь делаю неправильно?
Здесь используется Series.str.replace для замены подстроки по умолчанию и Series.replace для замены не подстроки, поэтому вместо этого можно использовать один или несколько пробелов ' '
использовать \s+
с:
#added second str.replace
df['Value'] = df['Value'].str.replace(',', '.').str.replace('\s+', '').astype(float)
#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)
Вам не хватает второй ул.