Welcome to OGeek Q&A 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 Reply

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...