The problem is that you do not do any type conversion of the numpy array. You calculate a float32 variable and put it as an entry into a float64 numpy array. numpy then converts it properly back to float64

Try someting like this:

a = np.zeros(4,dtype="float64") 
print a.dtype
print type(a[0])
a = np.float32(a)
print a.dtype
print type(a[0])

The output (tested with python 2.7)

float64
<type 'numpy.float64'>
float32
<type 'numpy.float32'>

a is in your case the array tree.tree_.threshold

Answer from Glostas on Stack Overflow
🌐
IncludeHelp
includehelp.com › python › how-to-convert-numpy-array-type-and-values-from-float64-to-float32.aspx
Python - How to convert NumPy array type and values from Float64 to Float32?
# Import numpy import numpy as np # Creating a numpy array arr = np.ones(4,dtype="float64") # Display original array print("Original Array:\n",arr,"\n") # Display type of original array print("type of Original Array:\n",arr.dtype,"\n") # Converting array into float32 arr = np.float32(arr) # Display type of modified array print("type of modified array:\n",arr.dtype,"\n")
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-7.php
NumPy: Array converted to a float type - w3resource
August 29, 2025 - # 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)
🌐
YouTube
youtube.com › watch
PYTHON : Convert numpy array type and values from Float64 ...
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
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.5 Manual
‘same_kind’ means only safe ... float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done. ‘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 ...
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.

🌐
w3resource
w3resource.com › python-exercises › numpy › basic › numpy-basic-exercise-41.php
NumPy: Convert numpy dtypes to native python types - w3resource
August 28, 2025 - np.float32(0) creates a NumPy scalar of data type float32 stores in the variable 'x' and initializes it with the value 0. print(type(x)) prints the type of 'x', which is a NumPy scalar type: ... The x.item() statement converts the NumPy scalar ...
🌐
Vultr Docs
docs.vultr.com › python › third party › numpy › array › astype()
Python Numpy array astype() - Convert Data Type
November 8, 2024 - 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)
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, ... such as numpy.float64 and numpy.float32 can be used within the astype() method for specifying the desired precision of floating-point numbers....
🌐
GitHub
github.com › numpy › numpy › issues › 12721
np.array(..., dtype=np.float32).astype(np.float16) doesn't handle denorms properly · Issue #12721 · numpy/numpy
January 11, 2019 - I think the reason for this is that all float16 operations use float32 internally, so this probably goes via float32: '%.40f' % np.array([2**-25 + 2**-38]).astype(np.float64).astype(np.float16)[0] # '0.0000000596046447753906250000000000000000' '%.40f' % np.array([2**-25 + 2**-38]).astype(np.float64).astype(np.float32).astype(np.float16)[0] # '0.0000000000000000000000000000000000000000'
🌐
NumPy
numpy.org › doc › stable › user › basics.types.html
Data types — NumPy v2.5 Manual
NumPy numerical types are instances of numpy.dtype (data-type) objects, each having unique characteristics. Once you have imported NumPy using import numpy as np you can create arrays with a specified dtype using the scalar types in the numpy top-level API, e.g. numpy.bool, numpy.float32, etc.
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: astype() to change dtype of an array | note.nkmk.me
February 4, 2024 - Even in operations between integers or floating-point numbers, if their bit sizes differ, the result is converted to the type with the larger bit size. a_int16 = np.array([1, 2, 3], np.int16) a_int32 = np.array([1, 2, 3], np.int32) print((a_int16 + a_int32).dtype) # int32 a_float16 = np.array([1, 2, 3], np.float16) a_float32 = np.array([1, 2, 3], np.float32) print((a_float16 + a_float32).dtype) # float32
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.1 Manual
‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done. ... 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 › doc › 2.1 › user › basics.types.html
Data types — NumPy v2.1 Manual
>>> np.array([1, 2, 3], dtype='f') ... data type objects, including how to specify parameters like the byte order. To convert the type of an array, use the .astype() method....
Top answer
1 of 13
574

Use val.item() to convert most NumPy values to a native Python type:

import numpy as np

# for example, numpy.float32 -> python float
val = np.float32(0)
pyval = val.item()
print(type(pyval))         # <class 'float'>

# and similar...
type(np.float64(0).item()) # <class 'float'>
type(np.uint32(0).item())  # <class 'int'>
type(np.int16(0).item())   # <class 'int'>
type(np.cfloat(0).item())  # <class 'complex'>
type(np.datetime64(0, 'D').item())  # <class 'datetime.date'>
type(np.datetime64('2001-01-01 00:00:00').item())  # <class 'datetime.datetime'>
type(np.timedelta64(0, 'D').item()) # <class 'datetime.timedelta'>
...

(A related method np.asscalar(val) was deprecated with 1.16, and removed with 1.23).


For the curious, to build a table of conversions of NumPy array scalars for your system:

for name in dir(np):
    obj = getattr(np, name)
    if hasattr(obj, 'dtype'):
        try:
            if 'time' in name:
                npn = obj(0, 'D')
            else:
                npn = obj(0)
            nat = npn.item()
            print('{0} ({1!r}) -> {2}'.format(name, npn.dtype.char, type(nat)))
        except:
            pass

There are a few NumPy types that have no native Python equivalent on some systems, including: clongdouble, clongfloat, complex192, complex256, float128, longcomplex, longdouble and longfloat. These need to be converted to their nearest NumPy equivalent before using .item().

2 of 13
45

If you want to convert (numpy.array OR numpy scalar OR native type OR numpy.darray) TO native type you can simply do :

converted_value = getattr(value, "tolist", lambda: value)()

tolist will convert your scalar or array to python native type. The default lambda function takes care of the case where value is already native.

🌐
TutorialsPoint
tutorialspoint.com › convert-masked-array-elements-to-float-type-in-numpy
Convert Masked Array elements to Float Type in Numpy
February 22, 2022 - import numpy as np import numpy.ma ... the Masked Array print(" Our Masked Array Dimensions... ",maskArr.ndim) # To convert masked array to float type, use the ma.MaskedArray.__float__() method in Numpy print(" Result Converted to float type......
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.6.dev0 Manual
‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done. ‘same_value’ means any data conversions may be done, but the values must not change, including rounding of floats or overflow of ints · Added 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.