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
Converting a NumPy ndarray to a ... element. The ndarray.item() method is generally the most robust and recommended approach for extracting a Python scalar of its natural type, while float(ndarray) is concise if you always want a Python float....
Discussions

python - How to properly cast mpmath matrix to numpy ndarray ( and mpmath.mpf to float) - Stack Overflow
I'm working with mpmath python library to gain precision during some computations, but i need to cast the result in a numpy native type. More precisely i need to cast an mpmath matrix (that contains mpf object types) in an numpy.ndarray (that contains float types). More on stackoverflow.com
🌐 stackoverflow.com
Preventing numpy from converting float type to numpy.int64 type
Numpy arrays have a defined data type. eta_hat is an array of dtype int64, because that's how you initialized it in the first place: as the docs say, if no type is given explicitly then "the type will be determined as the minimum type required to hold the objects in the sequence". So the solution is to explicitly make it an array of floats: eta_hat = numpy.array( [ [0], [0], [0] ], dtype=float) More on reddit.com
🌐 r/learnpython
3
1
April 3, 2023
Fastest way to convert numpy array to tuple of 1s and zeros?
import numpy as np x = np.array([1,2,3,0,0,1,2,3,0]) x[np.flatnonzero(x)] = 1 result = tuple(x) print(result) know more: https://numpy.org/doc/stable/reference/generated/numpy.flatnonzero.html More on reddit.com
🌐 r/learnpython
6
1
August 14, 2021
What's the appropriate type-hint for a function that can accept a list of floats OR a numpy array?
If your function accepts an array-like input that you intend to treat as an array, I think the "correct" thing to do is to run that input through one of the numpy.as*array() or numpy.atleast_*() functions before you use it. In both your examples, I think numpy.atleast_1d would probably be sensible. By the way, numpy does have 0-D arrays, so something like this can pass static checking and then fail at runtime if you don't run it through atleast_1d: import numpy as np import numpy.typing as npt myvar: npt.NDArray = np.array(1) print(myvar[0]) # or even print(len(myvar)) The type hints aren't enough on their own. More on reddit.com
🌐 r/learnpython
3
3
July 8, 2023
🌐
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 - It’s a form of in-place reassignment, not true in-place conversion which NumPy doesn’t support due to fixed data types . ... Explanation: Here, a is converted to float using astype(float) and reassigned to itself, updating the array without keeping the original. np.vectorize() turns a regular Python function like float() into a NumPy-style function that can operate element-wise over arrays.
🌐
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.
🌐
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.
🌐
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)
🌐
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
Find elsewhere
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: astype() to change dtype of an array | note.nkmk.me
February 4, 2024 - The object type is a special data type that stores pointers to Python objects. This means that the actual data for each element is stored in a separate memory space, enabling an ndarray to hold pointers to data of different types. a_object = np.array([1, 0.1, 'abc'], dtype=object) print(a_object) # [1 0.1 'abc'] print(a_object.dtype) # object print(type(a_object[0])) print(type(a_object[1])) print(type(a_object[2])) # <class 'int'> # <class 'float'> # <class 'str'> source: numpy_dtype.py ·
🌐
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
🌐
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 - By specifying float as the argument, the new array float_array has the same values as int_array but with a float data type. NumPy data type objects such as numpy.float64 and numpy.float32 can be used within the astype() method for specifying ...
🌐
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 ...
🌐
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()?
🌐
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
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.ndarray.html
numpy.ndarray — NumPy v2.1 Manual
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]]) ... >>> np.ndarray((2,), buffer=np.array([1,2,3]), ... offset=np.int_().itemsize, ... dtype=int) # offset = 1*itemsize, i.e. skip first element array([2, 3]) ... View of the transposed array. ... Python buffer object pointing to the start of the array’s data.
🌐
NumPy
numpy.org › doc › stable › user › quickstart.html
NumPy quickstart — NumPy v2.4 Manual
When arange is used with floating point arguments, it is generally not possible to predict the number of elements obtained, due to the finite floating point precision. For this reason, it is usually better to use the function linspace that receives as an argument the number of elements that we want, instead of the step: >>> from numpy import pi >>> np.linspace(0, 2, 9) # 9 numbers from 0 to 2 array([0.
🌐
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))
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.html
numpy.ndarray — NumPy v2.4 Manual
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]]) ... >>> np.ndarray((2,), buffer=np.array([1,2,3]), ... offset=np.int_().itemsize, ... dtype=int) # offset = 1*itemsize, i.e. skip first element array([2, 3]) ... View of the transposed array. ... Python buffer object pointing to the start of the array’s data.