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.

Answer from hpaulj on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › using-numpy-to-convert-array-elements-to-float-type
Using NumPy to Convert Array Elements to Float Type - GeeksforGeeks
July 15, 2025 - This approach reuses the astype() method like before, but here you overwrite the original array with the converted one. It’s a form of in-place reassignment, not true in-place conversion which NumPy doesn’t support due to fixed data types .
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.

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               ])
🌐
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)
🌐
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...
🌐
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.
🌐
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 - Dividing the integer array by 1.0 implicitly converts the integers to floats because the division operation promotes the result to the more general data type. ... import numpy as np int_array = np.array([7, 14, 21, 28]) float_array = int_array ...
Find elsewhere
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.asarray.html
numpy.asarray — NumPy v2.4 Manual
Convert input to an ndarray with column-major memory order. ... Similar function which checks input for NaNs and Infs. ... Create an array from an iterator. ... Construct an array by executing a function on grid positions. ... Try it in your browser! ... >>> a = np.array([1, 2], dtype=np.float32) >>> np.shares_memory(np.asarray(a, dtype=np.float32), a) True >>> np.shares_memory(np.asarray(a, dtype=np.float64), a) False
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-convert-numpy-array-to-list
Convert NumPy Array to List in Python Easily | DigitalOcean
April 19, 2025 - Learn how to convert a NumPy array to a Python list using simple methods with code examples. Ideal for beginners and data scientists working with NumPy.
🌐
Vultr Docs
docs.vultr.com › python › third-party › numpy › array › astype
Python Numpy array astype() - Convert Data Type | Vultr Docs
November 8, 2024 - This code converts an array of integers to an array of floats. The output will be [1.0, 2.0, 3.0, 4.0]. The method creates a new array with the specified data type and does not modify the original array. Understand that astype() can handle a wide range of data types. Create an array and convert it to different data types to see the effects. ... import numpy as np data = np.array([1.1, 2.2, 3.3, 4.4]) int_data = data.astype(int) bool_data = data.astype(bool) print("Integer conversion:", int_data) print("Boolean conversion:", bool_data) Explain Code
🌐
GitHub
github.com › numpy › numpy › issues › 18557
numpy converts to float if given a list of numpy.uint64 mixed with python ints · Issue #18557 · numpy/numpy
January 3, 2021 - If a python list argument to np.array contains a mixture of int and np.uint64, the array will have dtype=np.float64. Which results in a loss of information, since values are not exactly representable by float64. import numpy as np def print_array(a): print(a.dtype, a) large = 2**63 - 1 print_array(np.array([-1, large])) print_array(np.array([-1, np.int64(large)])) print_array(np.array([-1, np.uint64(large)]))
Author   maxnoe
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.tolist.html
numpy.ndarray.tolist — NumPy v2.4 Manual
>>> a = np.array([[1, 2], [3, 4]]) >>> list(a) [array([1, 2]), array([3, 4])] >>> a.tolist() [[1, 2], [3, 4]]
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.1 Manual
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.
Top answer
1 of 3
8

Yes, actually when you use Python's native float to specify the dtype for an array , numpy converts it to float64. As given in documentation -

Note that, above, we use the Python float object as a dtype. NumPy knows that int refers to np.int_, bool means np.bool_ , that float is np.float_ and complex is np.complex_. The other data-types do not have Python equivalents.

And -

float_ - Shorthand for float64.

This is why even though you use float to convert the whole array to float , it still uses np.float64.

According to the requirement from the other question , the best solution would be converting to normal float object after taking each scalar value as -

float(new_array[0])

A solution that I could think of is to create a subclass for float and use that for casting (though to me it looks bad). But I would prefer the previous solution over this if possible. Example -

In [20]: import numpy as np

In [21]: na = np.array([1., 2., 3.])

In [22]: na = np.array([1., 2., 3., np.inf, np.inf])

In [23]: type(na[-1])
Out[23]: numpy.float64

In [24]: na[-1] - na[-2]
C:\Anaconda3\Scripts\ipython-script.py:1: RuntimeWarning: invalid value encountered in double_scalars
  if __name__ == '__main__':
Out[24]: nan

In [25]: class x(float):
   ....:     pass
   ....:

In [26]: na_new = na.astype(x)


In [28]: type(na_new[-1])
Out[28]: float                           #No idea why its showing float, I would have thought it would show '__main__.x' .

In [29]: na_new[-1] - na_new[-2]
Out[29]: nan

In [30]: na_new
Out[30]: array([1.0, 2.0, 3.0, inf, inf], dtype=object)
2 of 3
3

You can create an anonymous type float like this

>>> new_array = my_array.astype(type('float', (float,), {}))
>>> type(new_array[0])
<type 'float'>