1

When I try:

df['Value'] = df['Value'].str.replace(',', '.').replace(' ', '').astype(float)

It would throw below error:

ValueError: could not convert string to float: '-1 750.5'

But when I use:

df['Value'] = df['Value'].apply(
    lambda x: float(x.replace(',', '.').replace(' ', '')))

It would work. What I am doing wrong here?

1
  • 3
    You are missing a second str. Commented Dec 15, 2020 at 12:06

1 Answer 1

2

Here is used Series.str.replace for default substring replacement and Series.replace for not substring replacement, so is possible for match one or more whitespaces instead ' ' use \s+ with:

#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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.