-2

I got an error in my code while converting string to character.

This is my dataframe image:

Photo

This how I remove the unit in the data:

Photo

and then while converting with:

for i in ['Power']:
    data[i] = data[i].astype(float)

I got the following error message:

Error message

4
  • 3
    Fun fact: if you google your title, you'll get a link to identical question with answers. Commented Apr 29, 2021 at 9:54
  • stackoverflow.com/questions/39125665/… Commented Apr 29, 2021 at 9:56
  • You left a space after every number. You should also remove space to convert sting into float. Commented Apr 29, 2021 at 10:00
  • i google it, and try the solution but still get that error message Commented Apr 29, 2021 at 10:49

1 Answer 1

0
import pandas as pd
data = {'Power': ['58.6 bhp', '126.2 bhp', '88.7 bhp']}
df = pd.DataFrame(data)


df=df.replace({'Power':'[a-z]'},'',regex=True) 

you can use lambda for row wise operation and convert to "float" as below :

df['Power']=df['Power'].apply(lambda row: float(row))

notebook Image

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.