You may want to use the ndarray.item method, as in a.item(). This is also equivalent to (the now deprecated) np.asscalar(a). This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,

>>> a = np.asarray(1).view()
>>> a.item()  # correct
1

>>> a[0]  # breaks
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array


>>> a = np.asarray([[2]])
>>> a.item()  # correct
2

>>> a[0]  # bad result
array([2])

This also has the benefit of throwing an exception if the array is not actually a scalar, while the a[0] approach will silently proceed (which may lead to bugs sneaking through undetected).

>>> a = np.asarray([1, 2])
>>> a[0]  # silently proceeds
1
>>> a.item()  # detects incorrect size
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: can only convert an array of size 1 to a Python scalar
Answer from Aaron Voelker on Stack Overflow
🌐
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 ...
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 numpy int to float with separate numpy array? - Stack Overflow
I have a huge data of numpy memory error problem, I try to use slicing to handle it like following How to merge two large numpy arrays if slicing doesn't resolve memory error? Slicing is work... More on stackoverflow.com
🌐 stackoverflow.com
np.float64(array) returns scalar for any single-element array (unlike np.float32, np.int64, etc.)
There was an error while loading. Please reload this page · Hi all, I'm reporting a problem when using np.float64 as a constructor More on github.com
🌐 github.com
14
April 27, 2018
Prevent numpy array from turning my floats into strings
numpy arrays are homogenous, i.e. they require that every element has the same type. Since calling asarray() on a list of tuples results in a 2 dimensional array, I assume this is why your values are being coerced. (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?) Assigning newarray = oldarray.astype(float) works as expected for me, however it converts every element to a float, including the ones that were originally strings. If this is what you wanted, then you can solve the problem by setting list1 = map(float, [list of strings])) to begin with. More on reddit.com
🌐 r/learnpython
7
10
May 5, 2015
🌐
GitHub
github.com › numpy › numpy › issues › 3161
Single element array passed to `np.float64` returns as numpy scalar, not array · Issue #3161 · numpy/numpy
March 21, 2013 - import numpy as np # Returns float 0.699..., not array([0.699]) np.float64(np.array([0.7], dtype=np.float64)) # Broken for conversion within floats; returns 0.5 np.float64(np.array([0.5], dtype=np.float32)) # Broken for conversion from uint; returns 42.0 np.float64(np.array([42], dtype=np.uint8)) # Works as expected for 2-element arrays np.float64(np.array([0.7, 0.7], dtype=np.float64)) # np.float32() and np.uint8() properly return arrays np.float32(np.array([0.7], dtype=np.float64) # array([0.699], dtype=float32) np.uint8(np.array([42.], dtype=np.float64) # array([4], dtype=uint8)
Author   JDWarner
🌐
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 ...
🌐
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 - Original longdouble array: [3.14159265]Converted float array using astype(): [3.14159265]Converted float array using new array creation: [3.14159265] We can also specify the data type during array creation using the dtype parameter. This method is particularly useful when creating a new array with a specific data type. ... import numpy as np # Example NumPy array (integer) integer_array = np.array(["1.1", "2.2", "3.3", "4.4"]) # Convert to float specifying dtype float_array = np.array(integer_array, dtype=float) print("Original Array (Integer):", integer_array) print("Converted Array (Float):", float_array)
🌐
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.
🌐
Codegive
codegive.com › blog › numpy_ndarray_to_float.php
Numpy ndarray to float
Extract one specific element from the array and convert that element to a float. Reduce (aggregate) the array to a single numerical value (e.g., its mean, sum, maximum, etc.) and then convert that resulting scalar* to a float. Throughout this tutorial, we will differentiate between these scenarios.
🌐
YouTube
youtube.com › hey delphi
Array : Convert list or numpy array of single element to float in python - YouTube
Array : Convert list or numpy array of single element to float in pythonTo Access My Live Chat Page, On Google, Search for "hows tech developer connect"I pro...
Published   May 1, 2023
Views   2
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 - 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 ...
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.

🌐
Educative
educative.io › answers › how-to-convert-data-types-of-arrays-using-numpy-in-python
How to convert data types of arrays using NumPy in Python
The data types in Numpy and their ... from the numpy library. We use the array() method to create an array. Then, we instruct the array to create a float data type, with the f to parameter dtype....
🌐
Statology
statology.org › home › how to fix: only size-1 arrays can be converted to python scalars
How to Fix: Only size-1 arrays can be converted to Python scalars
November 10, 2021 - import numpy as np #create NumPy array of float values x = np.array([3, 4.5, 6, 7.7, 9.2, 10, 12, 14.1, 15]) Now suppose we attempt to convert this array of float values to an array of integer values: #attempt to convert array to integer values np.int(x) TypeError: only size-1 arrays can be converted to Python scalars · We receive a TypeError because the np.int() function only accepts single values, not an array of values.
🌐
NumPy
numpy.org › devdocs › user › basics.types.html
Data types — NumPy v2.5.dev0 Manual
There are some exceptions, such as when code requires very specific attributes of a scalar or when it checks specifically whether a value is a Python scalar. Generally, problems are easily fixed by explicitly converting array scalars to Python scalars, using the corresponding Python type function (e.g., int, float, complex, str).
🌐
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.
🌐
GitHub
github.com › sympy › sympy › issues › 13637
products with arrays with only one element convert to float · Issue #13637 · sympy/sympy
November 24, 2017 - products with arrays with only one element convert to float#13637 · Copy link · When multiplying a numpy array with more than one entries, sympy entities (such as sympy.Rational) correctly translate into the array: import numpy import sympy print(sympy.Rational(1, 2) * numpy.array([1, 1])) [1/2 1/2] If, however, the array only has length 1, the values are converted into floats: print(sympy.Rational(1, 2) * numpy.array([1])) 0.500000000000000 ·
🌐
GitHub
github.com › numpy › numpy › issues › 10995
np.float64(array) returns scalar for any single-element array (unlike np.float32, np.int64, etc.) · Issue #10995 · numpy/numpy
April 27, 2018 - scalar = 0.0 # example a = np.array([[scalar]]) assert type(a) is np.ndarray assert type(np.float64(a)) is np.ndarray #AssertionError
Author   thejohnhoffer
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.item.html
numpy.ndarray.item — NumPy v2.4 Manual
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.
🌐
NumPy
numpy.org › doc › 2.1 › user › basics.types.html
Data types — NumPy v2.1 Manual
There are some exceptions, such as when code requires very specific attributes of a scalar or when it checks specifically whether a value is a Python scalar. Generally, problems are easily fixed by explicitly converting array scalars to Python scalars, using the corresponding Python type function (e.g., int, float, complex, str).
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.5.dev0 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.