简体   繁体   中英

How to convert string list to float in python?

I have a list of prices in my training set which are:

print(Y_train[:5])
-->["12,702.25", "221.45", "3,173.0", "794.0", "1,83,825.75"]

I want to convert this string list to a float list where I want these commas(',') to be excluded as well. How can I do it?

The output has to be in like:

print(Y_train[:5])
-->[12702.25, 221.45, 3173.0, 794.0, 183825.75]

Chris proposed the solution first in a comment , so full credit to him, I just want to put an end to these shameful answers.

raw_str_list = ['1,234.5', '372,737,000.993']
res_list = [float(curr.replace(',', '')) for curr in raw_str_list]

It is very simple what you have to do is add a new list and convert it into a float for example newList = [float(i) for i in Y_train]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM