Skip to content Skip to sidebar Skip to footer

Convert Strings In List To Float

this issue is driving me nuts. I have a scrapped data from a website and put those data into a dictionary. As a result I have a couple of lists and one of those lists looks like th

Solution 1:

you can use map and lambda to remove comma and convert the list of string floats to list of floats

result = list(map(lambda x: float(x.replace(",", "")), list_of_string_floats))

for integers it would be

result = list(map(lambda x: int(x.replace(",", "")), list_of_string_ints))

There is no need to use numpy


Solution 2:

You first have to get rid of the ",".

s = '7,051,156,075,145'
f = float(s.replace(',',''))

After this, f is the float value of the given string.

For the whole thing, you can do this:

float_list = [float(s.replace(',','')) for s in string_list]

Solution 3:

The most readable if L is your original list:

[[float(x) for x in s.split(',')] for s in L ]  

Solution 4:

check if that works

print map(lambda x: float("".join(x.split(","))), a)

https://repl.it/H6ZL


Post a Comment for "Convert Strings In List To Float"