0

I have a dataframe in each columns I have numbers but the type is object! how I can convert object to float?

I tried this : pd.to_numeric(df['Close_x'],errors='coerce')

but the error says:

TypeError: arg must be a list, tuple, 1-d array, or Series

I tried concatenated['Close_x'].astype(float)

the error says:

ValueError: could not convert string to float: '1,001.96'

1 Answers1

1

These numbers have , as a separator so first, you need to replace it with an empty string, then convert it to a floating-point number.

df = pd.DataFrame(['1,001.96', '1001.98'], columns=['value'])
pd.to_numeric(df['value'].replace(',', '',regex=True))

or

df.apply(lambda x: x.str.replace(',', '')).astype(float)

Note: df.apply is slower than pd.to_numeric for large dataframes

Vishnudev
  • 9,498
  • 1
  • 15
  • 50