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
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.

🌐
Codegive
codegive.com › blog › numpy_ndarray_to_float.php
Numpy ndarray to float
This tutorial will guide you through the process of converting a NumPy ndarray to a Python float. This seemingly simple task has nuances, especially depending on whether your ndarray contains a single element (a scalar) or multiple elements.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.__float__.html
numpy.ndarray.__float__ — NumPy v1.26 Manual
Back to top · Choose version · GitHub · Choose version · GitHub · method · ndarray.__float__(self)# On this page
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-7.php
NumPy: Array converted to a float type - w3resource
August 29, 2025 - Original array [1, 2, 3, 4] Array converted to a float type: [ 1. 2. 3. 4.] ... x = np.asfarray(a): The np.asfarray() function converts the given list ‘a’ into a one-dimensional NumPy array with a floating-point data type (by default, it ...
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.ndarray.__float__.html
numpy.ndarray.__float__ — NumPy v2.4.dev0 Manual
Back to top · Choose version · GitHub · Choose version · GitHub · method · ndarray.__float__(self)# On this page
🌐
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 - Universal functions, or ufuncs, are functions that operate element-wise on arrays. NumPy provides ufuncs for various operations, including data type conversion. The np.float64() ufunc is used to convert the array to the float data type.
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.ndarray.html
numpy.ndarray — NumPy v2.1 Manual
These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray. ... >>> import numpy as np >>> np.ndarray(shape=(2,2), dtype=float, order='F') array([[0.0e+000, 0.0e+000], # random [ nan, 2.5e-323]])
🌐
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 - If we want to convert it into a float, we can call the defined function where we can write a code to apply float() method on the item. ... # Import numpy import numpy as np # Creating a numpy array arr = np.array([4]) # Display original array print("Original Array:\n", arr, "\n") # Converting ...
Find elsewhere
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.4 Manual
June 22, 2021 - ‘same_value’ means any data conversions may be done, but the values must not change, including rounding of floats or overflow of ints · New in version 2.4: Support for 'same_value' was added. ... If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
🌐
Google Groups
groups.google.com › g › cython-users › c › Ubh2nG0_R9g
Converting float * to numpy array
>> Anyway, here is my simple problem: >> I have a C function that returns a float *, and I want to build a numpy >> array with it, and return it to python. >> >> 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 i in range(num_elements): > myarray[i] = pfArray[i] What about numpy.frombuffer()?
🌐
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 - Converting numerical data types is a common task in data processing and analysis using Python’s NumPy library. Specifically, users often face the need to transform an array of integers into an array of floats to allow for more precise calculations. For example, converting the NumPy integer array np.array([1, 2, 3]) to a float array np.array([1.0, 2.0, 3.0]).
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.5.dev0 Manual
‘same_value’ means any data conversions may be done, but the values must not change, including rounding of floats or overflow of ints · New in version 2.4: Support for 'same_value' was added. ... If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
🌐
Programiz
programiz.com › python-programming › numpy › methods › astype
NumPy astype()
import numpy as np # define a custom subclass of ndarray class CustomArray(np.ndarray): pass # create a custom subclass array array = np.array([1, 2, 3]).view(CustomArray) # convert the array to float, preserving the subclass floatArray1 = array.astype(float, subok=True) # convert the array to float, without preserving the subclass floatArray2 = array.astype(float, subok=False) print("Original Array Type:", type(array)) print("Float Array1 Type:", type(floatArray1)) print("Float Array2 Type:", type(floatArray2))
🌐
TutorialsPoint
tutorialspoint.com › convert-masked-array-elements-to-float-type-in-numpy
Convert Masked Array elements to Float Type in Numpy
February 22, 2022 - To convert masked array to float type, use the ma.MaskedArray.__float__() method in Numpy. A mask is either
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               ])
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.ndarray.__float__.html
numpy.ndarray.__float__ — NumPy v2.2 Manual
Back to top · Choose version · GitHub · Choose version · GitHub · method · ndarray.__float__(self)# On this page
🌐
Vultr Docs
docs.vultr.com › python › third-party › numpy › array › astype
Python Numpy array astype() - Convert Data Type | Vultr Docs
November 8, 2024 - Floating points are truncated, and any non-zero value is converted to True in the boolean array. Recognize that astype() can optimize memory usage by converting to more appropriate data types. Convert data types to less memory-intensive types when precision is not critical. ... import numpy as np high_precision = np.array([1.123456789, 2.987654321], dtype=np.float64) low_precision = high_precision.astype(np.float32) print("High precision:", high_precision) print("Low precision:", low_precision) Explain Code