Home > front end >  pandas conversion to float
pandas conversion to float

Time:03-16

I am trying to convert -2 which currently has datatype as obj into float with the help of .astypte(float) but it's not working

input data: enter image description here

output data: enter image description here

CodePudding user response:

Use str.rstrip:

df['% Return'] = df['% Return'].str.rstrip('%').astype(float)

or, if there is a possibility that the column also contains invalid data, use pandas.to_numeric:

df['% Return'] = pd.to_numeric(df['% Return'].str.rstrip('%'), errors='coerce')

CodePudding user response:

another way by correcting your code (using your idea)

df['% Return']=df['% Return'].apply(lambda x: x.replace('%','')).astype(float)

or you can also use this

df['% Return']=df['% Return'].apply(lambda x: x[:-1]).astype(float)
  • Related