Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

pandas - how to convert all columns from object to float type

I trying to convert all columns with '$' amount from object to float type.

With below code i couldnt remove the $ sign.

input:

df[:] = df[df.columns.map(lambda x: x.lstrip('$'))]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can using extract

df=pd.DataFrame({'A':['$10.00','$10.00','$10.00']})
df.apply(lambda x : x.str.extract('(d+)',expand=False).astype(float))
Out[333]: 
      A
0  10.0
1  10.0
2  10.0

Update

df.iloc[:,9:32]=df.iloc[:,9:32].apply(lambda x : x.str.extract('(d+)',expand=False).astype(float))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...