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
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.5.dev0 Manual
When casting from complex to float or int. To avoid this, one should use a.real.astype(t).
🌐
Programiz
programiz.com › python-programming › numpy › methods › astype
NumPy astype()
The astype() method converts an array to a specified data type. import numpy as np # original array of integers integerArray = np.array([1, 2, 3, 4, 5]) # convert array to floating-point numbers floatArray = integerArray.astype(float) print(floatArray) # Output: [1.
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 - numpy astype from float32 to float16 - Stack Overflow
I would like to know how numpy casts from float32 to float16, because when I cast some number like 8193 from float32 to float16 using astype, it will output 8192 while 10000 of float32 casted into 10000 of float16. More on stackoverflow.com
🌐 stackoverflow.com
print(np.array([np.nan]).astype(int).astype(float)).
print() writes the string representation of its arguments to stdout. np.array() initializes an array. np.nan is the IEEE 754 floating point representation of Not a Number (NaN). np.array.astype() casts the array to the specified type (by default without checking whether the cast is safe). So this creates an array containing NaN (float), then casts it to int, then back to float. Because NaN can’t be represented as an int, you get a weird number. More on reddit.com
🌐 r/Numpy
4
2
May 4, 2021
ENH: Numpy arrays of floats converted to string using astype(str) have unexpected behaviour
Proposed new feature or change: When converting an array of very small floats to str, the astype() function occasionally returns scientific notation instead of a str representation of a float. This feels like an uninteded issue with the ... More on github.com
🌐 github.com
3
February 17, 2024
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.1 Manual
When casting from complex to float or int. To avoid this, one should use a.real.astype(t).
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.4 Manual
June 22, 2021 - When casting from complex to float or int. To avoid this, one should use a.real.astype(t).
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.

🌐
Vultr Docs
docs.vultr.com › python › third-party › numpy › array › astype
Python Numpy array astype() - Convert Data Type | Vultr Docs
November 8, 2024 - Such conversion can reduce memory usage, important for handling large datasets. The astype() function in NumPy makes it possible to convert the data type of array elements seamlessly.
🌐
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 - Explanation: Here, a string array a is converted to a float array res using astype(float), creating a new array without modifying the original. NumPy allows you to define the type of elements directly during the creation of the array using the ...
🌐
NumPy
numpy.org › doc › stable › user › basics.types.html
Data types — NumPy v2.4 Manual
There are 5 basic numerical types representing booleans (bool), integers (int), unsigned integers (uint) floating point (float) and complex. A basic numerical type name combined with a numeric bitsize defines a concrete type. The bitsize is the number of bits that are needed to represent a ...
Find elsewhere
🌐
W3Schools
w3schools.com › python › numpy › numpy_data_types.asp
NumPy Data Types
The astype() function creates a copy of the array, and allows you to specify the data type as a parameter. The data type can be specified using a string, like 'f' for float, 'i' for integer etc.
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: astype() to change dtype of an array | note.nkmk.me
February 4, 2024 - While ndarray supports element-wise ... # [1, 0.1, 'abcXYZ', 1, 0.1, 'abcXYZ'] ... The astype() method of ndarray allows for changing (casting) dtype....
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.2 Manual
When casting from complex to float or int. To avoid this, one should use a.real.astype(t).
🌐
NumPy
numpy.org › doc › 2.0 › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.0 Manual
When casting from complex to float or int. To avoid this, one should use a.real.astype(t).
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.astype.html
numpy.astype — NumPy v2.4 Manual
>>> import numpy as np >>> arr = np.array([1, 2, 3]); arr array([1, 2, 3]) >>> np.astype(arr, np.float64) array([1., 2., 3.]) Non-copy case: >>> arr = np.array([1, 2, 3]) >>> arr_noncpy = np.astype(arr, arr.dtype, copy=False) >>> np.shares_memory(arr, arr_noncpy) True ·
🌐
NumPy
numpy.org › doc › 2.3 › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.3 Manual
When casting from complex to float or int. To avoid this, one should use a.real.astype(t).
🌐
NumPy
numpy.org › devdocs › user › basics.types.html
Data types — NumPy v2.5.dev0 Manual
There are 5 basic numerical types representing booleans (bool), integers (int), unsigned integers (uint) floating point (float) and complex. A basic numerical type name combined with a numeric bitsize defines a concrete type. The bitsize is the number of bits that are needed to represent a ...
🌐
JAX Documentation
docs.jax.dev › en › latest › _autosummary › jax.numpy.astype.html
jax.numpy.astype — JAX documentation
>>> x = jnp.array([0, 1, 2, 3]) >>> x Array([0, 1, 2, 3], dtype=int32) >>> x.astype('float32') Array([0.0, 1.0, 2.0, 3.0], dtype=float32)
🌐
GitHub
github.com › numpy › numpy › issues › 25841
ENH: Numpy arrays of floats converted to string using astype(str) have unexpected behaviour · Issue #25841 · numpy/numpy
February 17, 2024 - This feels like an uninteded issue with the astype function, as there is no way to turn off the scientific notation as the notation is implied to be just a visual representation in the rest of the documentation. The only ways to convert the floats to the inteded string representation is to explicity declare it using a very slow and unvectorized for loop etc., or by using very strange or difficult methods like arr = np.vectorize(np.core.multiarray.dragon4_positional)(arr)
Author   Pigizoid
🌐
NumPy
numpy.org › doc › 2.0 › reference › generated › numpy.astype.html
numpy.astype — NumPy v2.0 Manual
>>> arr = np.array([1, 2, 3]); arr array([1, 2, 3]) >>> np.astype(arr, np.float64) array([1., 2., 3.]) Non-copy case: >>> arr = np.array([1, 2, 3]) >>> arr_noncpy = np.astype(arr, arr.dtype, copy=False) >>> np.shares_memory(arr, arr_noncpy) True ·