How do I convert all of the items in a list to floats? [duplicate]
Asked Answered
B

14

355

I have a script which reads a text file, pulls decimal numbers out of it as strings and places them into a list.

So I have this list:

my_list = ['0.49', '0.54', '0.54', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54']

How do I convert each of the values in the list from a string to a float?

I have tried:

for item in my_list:
    float(item)

But this doesn't seem to work for me.

Blaubok answered 23/10, 2009 at 15:33 Comment(2)
Don't use list as a variable name.Pentstemon
To elaborate on above comment: using list as a variable name will shadow the built-in list constructor thus not allowing you to use that in the same scopeHeart
L
623
[float(i) for i in lst]

to be precise, it creates a new list with float values. Unlike the map approach it will work in py3k.

Libelous answered 23/10, 2009 at 15:34 Comment(5)
For large array's, I would recommend using numpy: np.array(inp_list, dtype=np.float32). You don't even have to specify if it's a float and just use: np.array(inp_list)Kenaz
@Thomas Devoogdt : I think you do need to specify the type, otherwise you will get a numpy array of stringsWidget
Please note that you have to assign [float(i) for i in lst] to something. E.g.: new_list = [float(i) for i in lst]Amaryllidaceous
Why doesn't python have a professional function to perform this operation?Marchpane
Depending on your security expectations, you might as well just "eval" like eval(my_list.join(", "))Ultramontane
P
164

map(float, mylist) should do it.

(In Python 3, map ceases to return a list object, so if you want a new list and not just something to iterate over, you either need list(map(float, mylist) - or use SilentGhost's answer which arguably is more pythonic.)

Pentstemon answered 23/10, 2009 at 15:34 Comment(1)
This is in fact a design sub-optimality in Python 3.Vaccinia
T
37

This would be an other method (without using any loop!):

import numpy as np
list(np.float_(list_name))
Tumbling answered 26/5, 2018 at 12:35 Comment(1)
Don't need to cast the np.array into the list again if you like to keep it as an np.array =)Stemma
C
17

float(item) do the right thing: it converts its argument to float and and return it, but it doesn't change argument in-place. A simple fix for your code is:

new_list = []
for item in list:
    new_list.append(float(item))

The same code can written shorter using list comprehension: new_list = [float(i) for i in list]

To change list in-place:

for index, item in enumerate(list):
    list[index] = float(item)

BTW, avoid using list for your variables, since it masquerades built-in function with the same name.

Chromonema answered 23/10, 2009 at 15:44 Comment(2)
Sorry, I did not get what in-place means here. How does it differ from the previous pythonic answer. Doesn't the conversion in the previous answer "[float(i) for i in lst]" retain the original list indexDashpot
@Dashpot Change original list vs. create a new one.Chromonema
B
16

you can even do this by numpy

import numpy as np
np.array(your_list,dtype=float)

this return np array of your list as float

you also can set 'dtype' as int

Brunhild answered 16/9, 2018 at 12:37 Comment(1)
But then you are returning a numpy array, not a list.Kermitkermy
R
7

You can use the map() function to convert the list directly to floats:

float_list = map(float, list)
Relativity answered 23/5, 2021 at 4:44 Comment(0)
M
3

You can use numpy to convert a list directly to a floating array or matrix.

    import numpy as np
    list_ex = [1, 0] # This a list
    list_int = np.array(list_ex) # This is a numpy integer array

If you want to convert the integer array to a floating array then add 0. to it

    list_float = np.array(list_ex) + 0. # This is a numpy floating array
Molotov answered 7/1, 2016 at 15:13 Comment(0)
T
2

This is how I would do it.

my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', 
    '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54', 
    '0.55', '0.55', '0.54']
print type(my_list[0]) # prints <type 'str'>
my_list = [float(i) for i in my_list]
print type(my_list[0]) # prints <type 'float'>
Tribulation answered 27/1, 2018 at 23:41 Comment(0)
M
2

you can use numpy to avoid looping:

import numpy as np
list(np.array(my_list).astype(float)
Magnolia answered 9/7, 2020 at 0:48 Comment(2)
Why would you use your approach rather than import numpy as np list(np.float_(list_name)) from the answer above?Amalee
There appears to be a missing closing parenthesis ).Spleeny
M
2
newlist = list(map(float, mylist))
Measurable answered 18/10, 2022 at 18:57 Comment(1)
Your answer is correct +1. From python 3.5 you can also do [*map(float, mylist)] to the same effect. Based on https://mcmap.net/q/55080/-getting-a-map-to-return-a-list-in-python-3-x-duplicateDaleth
N
0
import numpy as np
my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54', 
'0.55', '0.55', '0.54']
print(type(my_list), type(my_list[0]))   
# <class 'list'> <class 'str'>

which displays the type as a list of strings. You can convert this list to an array of floats simultaneously using numpy:

    my_list = np.array(my_list).astype(np.float)

    print(type(my_list), type(my_list[0]))  
    # <class 'numpy.ndarray'> <class 'numpy.float64'>
Nichy answered 16/5, 2018 at 12:33 Comment(0)
A
0

I had to extract numbers first from a list of float strings:

   df4['sscore'] = df4['simscore'].str.findall('\d+\.\d+')

then each convert to a float:

   ad=[]
   for z in range(len(df4)):
      ad.append([float(i) for i in df4['sscore'][z]])

in the end assign all floats to a dataframe as float64:

   df4['fscore'] = np.array(ad,dtype=float)
Administrator answered 5/3, 2019 at 13:34 Comment(0)
B
0
for i in range(len(list)): list[i]=float(list[i])
Burn answered 23/5, 2019 at 16:5 Comment(0)
I
-1

I have solve this problem in my program using:

number_input = float("{:.1f}".format(float(input())))
list.append(number_input)
Ichnite answered 4/9, 2018 at 13:53 Comment(1)
The OP states that he is reading from a text file. this answer does not apply to what has been asked.Timmy

© 2022 - 2024 — McMap. All rights reserved.