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")
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.5.dev0 Manual
‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
🌐
NumPy
numpy.org › doc › stable › user › basics.types.html
Data types — NumPy v2.4 Manual
>>> np.array([1, 2, 3], dtype='f') array([1., 2., 3.], dtype=float32) >>> np.array([1, 2, 3], dtype='d') array([1., 2., 3.], dtype=float64)
🌐
Medium
medium.com › @amit25173 › understanding-numpy-float64-a300ac9e096a
Understanding numpy.float64. If you think you need to spend $2,000… | by Amit Yadav | Medium
February 8, 2025 - You might be wondering: “Can I convert an existing array into float64?” · Absolutely! You can convert any NumPy array (or even a regular list) into float64 using the astype() method.
Top answer
1 of 3
8

Yes, actually when you use Python's native float to specify the dtype for an array , numpy converts it to float64. As given in documentation -

Note that, above, we use the Python float object as a dtype. NumPy knows that int refers to np.int_, bool means np.bool_ , that float is np.float_ and complex is np.complex_. The other data-types do not have Python equivalents.

And -

float_ - Shorthand for float64.

This is why even though you use float to convert the whole array to float , it still uses np.float64.

According to the requirement from the other question , the best solution would be converting to normal float object after taking each scalar value as -

float(new_array[0])

A solution that I could think of is to create a subclass for float and use that for casting (though to me it looks bad). But I would prefer the previous solution over this if possible. Example -

In [20]: import numpy as np

In [21]: na = np.array([1., 2., 3.])

In [22]: na = np.array([1., 2., 3., np.inf, np.inf])

In [23]: type(na[-1])
Out[23]: numpy.float64

In [24]: na[-1] - na[-2]
C:\Anaconda3\Scripts\ipython-script.py:1: RuntimeWarning: invalid value encountered in double_scalars
  if __name__ == '__main__':
Out[24]: nan

In [25]: class x(float):
   ....:     pass
   ....:

In [26]: na_new = na.astype(x)


In [28]: type(na_new[-1])
Out[28]: float                           #No idea why its showing float, I would have thought it would show '__main__.x' .

In [29]: na_new[-1] - na_new[-2]
Out[29]: nan

In [30]: na_new
Out[30]: array([1.0, 2.0, 3.0, inf, inf], dtype=object)
2 of 3
3

You can create an anonymous type float like this

>>> new_array = my_array.astype(type('float', (float,), {}))
>>> type(new_array[0])
<type 'float'>
Top answer
1 of 13
572

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.

Top answer
1 of 1
4

The result of np.sum(a) is a NumPy scalar, rather than an array. Operations involving only scalars use different casting rules from operations involving (positive-dimensional) NumPy arrays, described in the docs for numpy.result_type.

When an operation involves only scalars (including 0-dimensional arrays), the result dtype is determined purely by the input dtypes. The same is true for operations involving only (positive-dimensional) arrays.

However, when scalars and (positive-dimensional) arrays are mixed, instead of using the actual dtypes of the scalars, NumPy examines the values of the scalars to see if a "smaller" dtype can hold them, then uses that dtype for the type promotion. (The arrays do not go through this process, even if their values would fit in a smaller dtype.)

Thus,

np.sum(a)+1

is a scalar operation, converting 1 to a NumPy scalar of dtype int_ (either int32 or int64 depending on the size of a C long) and then performing promotion based on dtypes float32 and int32/int64, but

a+1

involves an array, so the dtype of 1 is treated as int8 for the purposes of promotion.

Since a float32 can't hold all values of dtype int32 (or int64), NumPy upgrades to float64 for the first promotion. (float64 can't hold all values of dtype int64, but NumPy won't promote to numpy.longdouble for this.) Since a float32 can hold all values of dtype int8, NumPy sticks with float32 for the second promotion.

If you use a number bigger than 1, so it doesn't fit in an int8:

In [16]: (a+1).dtype
Out[16]: dtype('float32')

In [17]: (a+1000000000).dtype
Out[17]: dtype('float64')

you can see different promotion behavior.

Find elsewhere
🌐
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, an integer array a is converted to a float array res using np.float64(), which casts the elements to 64-bit floating-point numbers efficiently. This approach reuses the astype() method like before, but here you overwrite the original array with the converted one. It’s a form of in-place reassignment, not true in-place conversion which NumPy doesn’t support due to fixed data types .
🌐
GitHub
github.com › numpy › numpy › issues › 14150
How to convert np.float32 to Python float easily? · Issue #14150 · numpy/numpy
May 29, 2019 - Hi, I try to convert np.float32 to a Python float in my project, and I find it's not eaisly. I have to convert it to str and then convert to float. Here is the code: Reproducing code example: import numpy as np x = np.float32(1.9) x.toli...
Author   ringsaturn
🌐
Quora
quora.com › What-is-np-float32-and-np-float64-in-numpy-in-simple-terms
What is np.float32 and np.float64 in numpy in simple terms? - Quora
Answer (1 of 2): np.float32 - It means that each value in the numpy array would be a float of size 32 bits. np.float64- It means that each value in the numpy array would be a float of size 64. If you are concerned about storing big numbers you should consider using float64, however, it takes mo...
🌐
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.
🌐
GitHub
github.com › astropy › astropy › issues › 6845
Converting float64 to float32 rounds off data in hdu object · Issue #6845 · astropy/astropy
July 26, 2017 - To save hardisk space, I wanted to convert my float64 fits images to float32. I used the hdulist[0].scale('float32') method to do that.
Author   indiajoe
Top answer
1 of 3
31

The tolist() method should do what you want. If you have a numpy array, just call tolist():

In [17]: a
Out[17]: 
array([ 0.        ,  0.14285714,  0.28571429,  0.42857143,  0.57142857,
        0.71428571,  0.85714286,  1.        ,  1.14285714,  1.28571429,
        1.42857143,  1.57142857,  1.71428571,  1.85714286,  2.        ])

In [18]: a.dtype
Out[18]: dtype('float64')

In [19]: b = a.tolist()

In [20]: b
Out[20]: 
[0.0,
 0.14285714285714285,
 0.2857142857142857,
 0.42857142857142855,
 0.5714285714285714,
 0.7142857142857142,
 0.8571428571428571,
 1.0,
 1.1428571428571428,
 1.2857142857142856,
 1.4285714285714284,
 1.5714285714285714,
 1.7142857142857142,
 1.857142857142857,
 2.0]

In [21]: type(b)
Out[21]: list

In [22]: type(b[0])
Out[22]: float

If, in fact, you really have python list of numpy.float64 objects, then @Alexander's answer is great, or you could convert the list to an array and then use the tolist() method. E.g.

In [46]: c
Out[46]: 
[0.0,
 0.33333333333333331,
 0.66666666666666663,
 1.0,
 1.3333333333333333,
 1.6666666666666665,
 2.0]

In [47]: type(c)
Out[47]: list

In [48]: type(c[0])
Out[48]: numpy.float64

@Alexander's suggestion, a list comprehension:

In [49]: [float(v) for v in c]
Out[49]: 
[0.0,
 0.3333333333333333,
 0.6666666666666666,
 1.0,
 1.3333333333333333,
 1.6666666666666665,
 2.0]

Or, convert to an array and then use the tolist() method.

In [50]: np.array(c).tolist()
Out[50]: 
[0.0,
 0.3333333333333333,
 0.6666666666666666,
 1.0,
 1.3333333333333333,
 1.6666666666666665,
 2.0]

If you are concerned with the speed, here's a comparison. The input, x, is a python list of numpy.float64 objects:

In [8]: type(x)
Out[8]: list

In [9]: len(x)
Out[9]: 1000

In [10]: type(x[0])
Out[10]: numpy.float64

Timing for the list comprehension:

In [11]: %timeit list1 = [float(v) for v in x]
10000 loops, best of 3: 109 µs per loop

Timing for conversion to numpy array and then tolist():

In [12]: %timeit list2 = np.array(x).tolist()
10000 loops, best of 3: 70.5 µs per loop

So it is faster to convert the list to an array and then call tolist().

2 of 3
11

You could use a list comprehension:

floats = [float(np_float) for np_float in np_float_list]
🌐
Vultr Docs
docs.vultr.com › python › third-party › numpy › array › astype
Python Numpy array astype() - Convert Data Type | Vultr Docs
November 8, 2024 - 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
🌐
NumPy
numpy.org › devdocs › user › basics.types.html
Data types — NumPy v2.5.dev0 Manual
>>> np.array([1, 2, 3], dtype='f') array([1., 2., 3.], dtype=float32) >>> np.array([1, 2, 3], dtype='d') array([1., 2., 3.], dtype=float64)
🌐
APXML
apxml.com › courses › essential-numpy-pandas › chapter-2-getting-started-numpy-arrays › array-data-types
NumPy Array Data Types (dtypes)
Notice in the last example, because the list contained both integers and a float, NumPy automatically inferred the most general type that could accommodate all elements, which is float64 in this case. You don't have to rely on NumPy's automatic inference. You can explicitly specify the desired data type when creating an array using the dtype argument. This is useful for controlling memory usage or ensuring a specific precision. import numpy as np # Specify float32 arr_float32 = np.array([1, 2, 3], dtype=np.float32) print(f"Array: {arr_float32}") print(f"Data Type: {arr_float32.dtype}") # Speci