import numpy

a = numpy.arange(0.5, 1.5, 0.1, dtype=numpy.float64)

print(a)

a = numpy.round(a.astype(numpy.float64), 1)

print (a)

print (a.tolist())

Output:

[0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4]
[0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4]
[0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4]

You can use numpy.round() with astype() method to round your float, getting something consistant upon tolist() conversion.

Answer from Synthaze on Stack Overflow
Top answer
1 of 2
4
import numpy

a = numpy.arange(0.5, 1.5, 0.1, dtype=numpy.float64)

print(a)

a = numpy.round(a.astype(numpy.float64), 1)

print (a)

print (a.tolist())

Output:

[0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4]
[0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4]
[0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4]

You can use numpy.round() with astype() method to round your float, getting something consistant upon tolist() conversion.

2 of 2
3

By the conversion via .tolist() you're not gaining or loosing any precision. You're just converting to another data type which chooses to represent itself differently. You seem to be thinking that by the conversion it turns the 0.8 into 0.7999999999999999, but the situation is, it has never been 0.8. This is due to limited floating point precision. You can verify yourself:

>>> import numpy
>>> a = numpy.arange(0.5, 1.5, 0.1, dtype=numpy.float64)
>>> a
array([0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2, 1.3, 1.4])
>>> a[3]
0.7999999999999999

The situation is that that every type can decide how its instances are represented via __repr__ or __str__. In this specific case np.ndarray decides to show a rounded version of its elements for more clarity. This can be controlled via numpy.set_printoptions. This function only affects how arrays are displayed:

>>> numpy.set_printoptions(floatmode='unique')
>>> a
array([0.5               , 0.6               , 0.7               ,
       0.7999999999999999, 0.8999999999999999, 0.9999999999999999,
       1.0999999999999999, 1.1999999999999997, 1.2999999999999998,
       1.4               ])

A note on np.arange from the docs:

When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases.

Here are the results for linspace:

>>> np.linspace(0.5, 1.5, 11)
array([0.5               , 0.6               , 0.7               ,
       0.8               , 0.9               , 1.                ,
       1.1               , 1.2000000000000002, 1.3               ,
       1.4               , 1.5               ])
Discussions

python - changing numpy array to float - Stack Overflow
I have a numpy array of type object. I want to find the columns with numerical values and cast them to float. Also I want to find the indices of the columns with object values. this is my attempt: More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to convert an array of strings to an array of floats in numpy? - Stack Overflow
Well, if you're reading the data in as a list, just do np.array(map(float, list_of_strings)) (or equivalently, use a list comprehension). (In Python 3, you'll need to call list on the map return value if you use map, since map returns an iterator now.) However, if it's already a numpy array of ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Convert NumPy array to Python list - Stack Overflow
How do I convert a NumPy array into a Python List? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Convert list or numpy array of single element to float in python - Stack Overflow
I have a function which can accept either a list or a numpy array. In either case, the list/array has a single element (always). I just need to return a float. So, e.g., I could receive: list_ =... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ using-numpy-to-convert-array-elements-to-float-type
Using NumPy to Convert Array Elements to Float Type - GeeksforGeeks
December 21, 2023 - Integer Array with Float64 Data Type: [1. 2. 3. 4. 5.] Float Array with Int32 Data Type: [1 2 3 4 5] ... This article will guide you through the process of convert a NumPy array to a list in Python, employing various methods and providing detailed examples for better understanding.
Top answer
1 of 3
23

Generally your idea of trying to apply astype to each column is fine.

In [590]: X[:,0].astype(int)
Out[590]: array([1, 2, 3, 4, 5])

But you have to collect the results in a separate list. You can't just put them back in X. That list can then be concatenated.

In [601]: numlist=[]; obj_ind=[]

In [602]: for ind in range(X.shape[1]):
   .....:     try:
   .....:         x = X[:,ind].astype(np.float32)
   .....:         numlist.append(x)
   .....:     except:
   .....:         obj_ind.append(ind)

In [603]: numlist
Out[603]: [array([ 3.,  4.,  5.,  6.,  7.], dtype=float32)]

In [604]: np.column_stack(numlist)
Out[604]: 
array([[ 3.],
       [ 4.],
       [ 5.],
       [ 6.],
       [ 7.]], dtype=float32)

In [606]: obj_ind
Out[606]: [1]

X is a numpy array with dtype object:

In [582]: X
Out[582]: 
array([[1, 'A'],
       [2, 'A'],
       [3, 'C'],
       [4, 'D'],
       [5, 'B']], dtype=object)

You could use the same conversion logic to create a structured array with a mix of int and object fields.

In [616]: ytype=[]

In [617]: for ind in range(X.shape[1]):
    try:                        
        x = X[:,ind].astype(np.float32)
        ytype.append('i4')
    except:
        ytype.append('O')       

In [618]: ytype
Out[618]: ['i4', 'O']

In [620]: Y=np.zeros(X.shape[0],dtype=','.join(ytype))

In [621]: for i in range(X.shape[1]):
    Y[Y.dtype.names[i]] = X[:,i]

In [622]: Y
Out[622]: 
array([(3, 'A'), (4, 'A'), (5, 'C'), (6, 'D'), (7, 'B')], 
      dtype=[('f0', '<i4'), ('f1', 'O')])

Y['f0'] gives the the numeric field.

2 of 3
2

I think this might help

def func(x):
  a = None
  try:
    a = x.astype(float)
  except:
    # x.name represents the current index value 
    # which is column name in this case
    obj.append(x.name) 
    a = x
  return a

obj = []
new_df = df.apply(func, axis=0)

This will keep the object columns as such which you can use later.

Note: While using pandas.DataFrame avoid using iteration using loop as this much slower than performing the same operation using apply.

๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ convert-list-or-numpy-array-of-single-element-to-float.aspx
Python - Convert list or NumPy array of single element to float
December 23, 2023 - # Import numpy import numpy as np # Creating a numpy array arr = np.array([4]) # Display original array print("Original Array:\n", arr, "\n") # Converting to float res = float(arr) # Display result print("Result:\n", res) ''' # YOU CAN ALSO USE THIS...
๐ŸŒ
Medium
medium.com โ€บ @whyamit404 โ€บ converting-numpy-ndarray-to-a-list-step-by-step-guide-defdfb09bcbe
Converting NumPy ndarray to a List (Step-by-Step Guide) | by whyamit404 | Medium
February 9, 2025 - import numpy as np # Mixed data type NumPy array ndarray_mixed = np.array([1, 'two', 3.0]) # Convert to list mixed_list = ndarray_mixed.tolist() print("Original NumPy Array:", ndarray_mixed) print("Converted List:", mixed_list) ... Why this matters: This is useful when youโ€™re working with datasets that include multiple data types. For instance, a dataset might have numerical IDs, textual labels, and floating-point values, and youโ€™d want to manipulate them all in a Python list for further processing.
Find elsewhere
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ 5 best ways to convert a numpy array from integers to floats
5 Best Ways to Convert a NumPy Array from Integers to Floats - Be on the Right Side of Change
February 20, 2024 - This approach directly casts each element in the original int_array to a float by iterating over every element with a list comprehension and then creating a new NumPy array from the resulting list. Method 1: Using astype() Function. Strengths: ...
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ numpy โ€บ python-numpy-exercise-7.php
NumPy: Array converted to a float type - w3resource
August 29, 2025 - Write a NumPy program to convert an array to a floating type. ... # Importing the NumPy library with an alias 'np' import numpy as np # Defining a Python list 'a' containing integers a = [1, 2, 3, 4] # Printing the original array 'a' print("Original array") print(a) # Converting the array 'a' to a NumPy array of type float using asfarray() x = np.asfarray(a) # Printing the array 'x' after converting to a float type print("Array converted to a float type:") print(x)
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ convert list to float python
How to Convert List to Float in Python | Delft Stack
February 2, 2024 - Lastly, list() is used to convert the NumPy array back to a regular Python list, resulting in resulting_list containing the converted float values. ... input_list: This is the parameter that represents the input list containing the original string items that you want to convert to a list of floats
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-convert-numpy-array-to-list
Convert NumPy Array to List in Python Easily | DigitalOcean
April 19, 2025 - As you can see, the tolist() method has successfully converted the complex, nested array with mixed types to a list, preserving the original structure and handling the mixed types correctly. A common mistake is using the built-in list() function on a multi-dimensional NumPy array, which results ...
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python โ€บ numpy
Convert between NumPy array and Python list | note.nkmk.me
January 23, 2024 - The data type (dtype) of the generated ndarray is automatically determined from the original list, but it can also be specified using the dtype argument. For more information about data type (dtype) in NumPy, see the following article. NumPy: Cast ndarray to a specific dtype with astype() a_1d_f = np.array(l_1d, dtype=float) print(a_1d_f) # [0.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ prevent numpy array from turning my floats into strings
r/learnpython on Reddit: Prevent numpy array from turning my floats into strings
May 5, 2015 -

Let's say I have 5 lists, list1, list2, list3, list4, list5.

The first 3 are lists of strings e.g. while the last 2 are lists of floats e.g.

list1  = ['1','2','3'...] 
list2 = list3 = list1
list4 = [1.0,2.0,3.0...]
list5 = list4

All lists are the same length.

I'd like to turn them into a numpy array, while preserving their original datatypes. I say

intermediateList = zip(list1,list2,list3,list4,list5)

which gives me a list (length=5) of lists, with the original data types preserved. Perfect.

However, when I try to convert to numpy.array

myArray=asarray(intermediateList)

numPy converts everything into numpy_string type, which is very irritating. I can now no longer perform numerical operations on list4 and list5 without re-converting the values to float.

(as a sidenote, if I were to try to fix this by saying

list5=list5.astype(float)

it will convert to float in the console, however when I call list5 again it is back to numpy_string! anyone know why?)

Any suggestions?

Top answer
1 of 3
31

The tolist() method should do what you want. If you have a numpy array, just call tolist():

In [17]: a
Out[17]: 
array([ 0.        ,  0.14285714,  0.28571429,  0.42857143,  0.57142857,
        0.71428571,  0.85714286,  1.        ,  1.14285714,  1.28571429,
        1.42857143,  1.57142857,  1.71428571,  1.85714286,  2.        ])

In [18]: a.dtype
Out[18]: dtype('float64')

In [19]: b = a.tolist()

In [20]: b
Out[20]: 
[0.0,
 0.14285714285714285,
 0.2857142857142857,
 0.42857142857142855,
 0.5714285714285714,
 0.7142857142857142,
 0.8571428571428571,
 1.0,
 1.1428571428571428,
 1.2857142857142856,
 1.4285714285714284,
 1.5714285714285714,
 1.7142857142857142,
 1.857142857142857,
 2.0]

In [21]: type(b)
Out[21]: list

In [22]: type(b[0])
Out[22]: float

If, in fact, you really have python list of numpy.float64 objects, then @Alexander's answer is great, or you could convert the list to an array and then use the tolist() method. E.g.

In [46]: c
Out[46]: 
[0.0,
 0.33333333333333331,
 0.66666666666666663,
 1.0,
 1.3333333333333333,
 1.6666666666666665,
 2.0]

In [47]: type(c)
Out[47]: list

In [48]: type(c[0])
Out[48]: numpy.float64

@Alexander's suggestion, a list comprehension:

In [49]: [float(v) for v in c]
Out[49]: 
[0.0,
 0.3333333333333333,
 0.6666666666666666,
 1.0,
 1.3333333333333333,
 1.6666666666666665,
 2.0]

Or, convert to an array and then use the tolist() method.

In [50]: np.array(c).tolist()
Out[50]: 
[0.0,
 0.3333333333333333,
 0.6666666666666666,
 1.0,
 1.3333333333333333,
 1.6666666666666665,
 2.0]

If you are concerned with the speed, here's a comparison. The input, x, is a python list of numpy.float64 objects:

In [8]: type(x)
Out[8]: list

In [9]: len(x)
Out[9]: 1000

In [10]: type(x[0])
Out[10]: numpy.float64

Timing for the list comprehension:

In [11]: %timeit list1 = [float(v) for v in x]
10000 loops, best of 3: 109 ยตs per loop

Timing for conversion to numpy array and then tolist():

In [12]: %timeit list2 = np.array(x).tolist()
10000 loops, best of 3: 70.5 ยตs per loop

So it is faster to convert the list to an array and then call tolist().

2 of 3
11

You could use a list comprehension:

floats = [float(np_float) for np_float in np_float_list]
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ generated โ€บ numpy.ndarray.astype.html
numpy.ndarray.astype โ€” NumPy v2.4 Manual
June 22, 2021 - Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order. ... When casting from complex to float or int.
๐ŸŒ
Google Groups
groups.google.com โ€บ g โ€บ cython-users โ€บ c โ€บ Ubh2nG0_R9g
Converting float * to numpy array
>> >> I have some thing like: >> >> cimport numpy as np >> >> cdef float *pfArray = my_c_function() >> cdef np.ndarray myarray >> # Well I'm quite lost here >> > > You can simply iterate over your C array and copy the values to the > numpy array : > > myarray = np.empty(num_elements) > for ...