0

I'm struggling to my df['High'] into float, I'm not sure what I did wrong or its any other way to convert them. Many thanks in advance.

enter image description here

df.info() details with High, Low, Volume as object type

enter image description here

error codes

dynosaur_
  • 33
  • 2

1 Answers1

1

It's because you have a '-' in that column. Likewise, changing to just empty string of '' will also not convert to float. You can't convert that to a float because it's obviously not a float.

You can replace the '-' with nan

import pandas as pd
import numpy as np

df = pd.DataFrame({'High':['20.1','100.3','99','-']})

df['High'] = df['High'].replace('-', np.nan)
df['High'] = df['High'].astype(float)

Output:

Before:

df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   High    4 non-null      object
dtypes: object(1)
memory usage: 160.0+ bytes

After:

df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   High    3 non-null      float64
dtypes: float64(1)
memory usage: 160.0 bytes
chitown88
  • 27,527
  • 4
  • 30
  • 59