Remove space in string representing numbers in dataframe

Viewed 31

I have a dataframe with numbers like '1 234' but they are string objects. And I tried to convert in float with df[column].apply(pandas.to_numeric, errors='ignore', downcast='float'). I want to iterate of each column because the dataframe change and columns too. The problem is it cannot convert in float because of the space. Is there a solution to remove space and then convert in float ?

enter image description here

2 Answers

Try str.replace -

df = pd.DataFrame({'A': ['1 234', '2341']})
df['A'].str.replace(' ', '').astype(float)

Output

0    1234.0
1    2341.0
Name: A, dtype: float64

You can use:

pd.to_numeric(df['column'].str.replace(r'\D+', '', regex=True))

Or, if you expect decimals:

pd.to_numeric(df['column'].str.replace(r'[^\d.]+', '', regex=True), errors='coerce')
Related