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
🌐
GitHub
github.com › numpy › numpy › issues › 14150
How to convert np.float32 to Python float easily? · Issue #14150 · numpy/numpy
July 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
Discussions

numpy - How to force python float operation on float32 rather than float64? - Stack Overflow
I want to do some math operations ... than on float64 type. I need do these operations on number or numpy.array, and also some numpy math functions, such as sqrt mean. How do I do this? ... >>>PI=3.1415926535897 >>> print PI*PI 9.86960440109 >>> PI32=numpy.float32(PI) >>> print PI32*PI32 9.86961 · If you want to do math operation on float32, convert the operands ... More on stackoverflow.com
🌐 stackoverflow.com
Converting float64 to float32 rounds off data in hdu object
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. More on github.com
🌐 github.com
8
November 13, 2017
How do I convert a python float to a Float32?
I am trying to iterate over a Python list and compare the values to those in a Mojo Float32 list, but I have not found a way of converting a Python float to any Mojo type for comparison. I’ve tried Float32(f.to_float64(… More on forum.modular.com
🌐 forum.modular.com
1
0
January 27, 2026
Is there an efficient way to convert a model with float32 params to float64?
Hi All, I was wondering if it’s at all possible to efficiently convert all my model parameters from float32 to float64? I’ve pretrained my model in float32, but when running it I get a NaN error but I know that model works within float64. So, I’d ideally like to just reformat my dtype. More on discuss.pytorch.org
🌐 discuss.pytorch.org
0
1
August 31, 2021
🌐
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?
For this purpose, we need to perform type conversion of the numpy array. We will calculate a Float32 variable and put it as an entry into a Float64 numpy array. numpy then converts it properly back to Float64.
🌐
GitHub
github.com › astropy › astropy › issues › 6845
Converting float64 to float32 rounds off data in hdu object · Issue #6845 · astropy/astropy
November 13, 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
🌐
Modular
forum.modular.com › mojo
How do I convert a python float to a Float32? - Mojo - Modular
January 27, 2026 - I am trying to iterate over a Python list and compare the values to those in a Mojo Float32 list, but I have not found a way of converting a Python float to any Mojo type for comparison. I’ve tried Float32(f.to_float64()), but to_float64() returns a PythonObject, and Float32 cannot convert a PythonObject.
🌐
PyTorch Forums
discuss.pytorch.org › t › is-there-an-efficient-way-to-convert-a-model-with-float32-params-to-float64 › 130767
Is there an efficient way to convert a model with float32 params to float64? - PyTorch Forums
August 31, 2021 - Hi All, I was wondering if it’s at all possible to efficiently convert all my model parameters from float32 to float64? I’ve pretrained my model in float32, but when running it I get a NaN error but I know that model wo…
Find elsewhere
🌐
Python⇒Speed
pythonspeed.com › articles › float64-float32-precision
The problem with float32: you only get 16 million values
February 1, 2023 - >>> arr = np.arange(0, 8388608, 0.5, dtype=np.float64) >>> arr[-4:] array([8388606. , 8388606.5, 8388607. , 8388607.5]) >>> arr[-4:].astype(np.float32) array([8388606. , 8388606.5, 8388607.
🌐
w3resource
w3resource.com › python-exercises › numpy › basic › numpy-basic-exercise-41.php
NumPy: Convert numpy dtypes to native python types - w3resource
August 28, 2025 - This problem involves writing a NumPy program to convert NumPy data types (dtypes) to native Python types. The task requires using NumPy's type conversion functions to transform NumPy-specific data types, such as numpy.int32 or numpy.float32, into their equivalent native Python types, like int or float.
🌐
NumPy
numpy.org › doc › stable › user › basics.types.html
Data types — NumPy v2.4 Manual
To convert the type of an array, use the .astype() method. For example: ... Note that, above, we could have used the Python float object as a dtype instead of numpy.float64. NumPy knows that int refers to numpy.int_, bool means numpy.bool, that float is numpy.float64 and complex is numpy.complex128.
🌐
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...
🌐
Google Groups
groups.google.com › g › julia-users › c › Lq2gQf4Ktp4
64 bit system: Force Float default to Float32
-E ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... Note also that while Float64 * Float32 (and other arithmetic ops) produce Float64, for other "less precise" numeric types, Float32 wins out, making ...
Top answer
1 of 13
573

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.

🌐
Python Forum
python-forum.io › thread-2181.html
pandas convert to tuple & float to float64
Dear Pandas Experts, I got two question on my Introduction to Python homework. The jupiter auto-grader expects in case 1 a float64 and in case 2 a tuple, not a list. case 1 newfour_2['GDPDiff']=np.subtract(newfour['2015'],newfour['2006']) ...
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'>
🌐
Reddit
reddit.com › r/learnpython › [beginner] how to best convert a 64bit integer to a 32 bit float
r/learnpython on Reddit: [beginner] How to best convert a 64bit integer to a 32 bit float
August 9, 2022 -

I was trying numpy for matrix calculations and I used it to solve simultaneous eqns.

I have a matrix, `answer` with desired values shown as:

[[4.]
[2.]
[5.]]

I realise that the dots are because the actual values are a float, so I tried `answer.tolist()`

This gives me:

[[3.9999999999999987], [1.9999999999999996], [4.999999999999998]]

In my program, I want to convert this to an integer, however using Python's `int()` function means it becomes: 3, 1, 4

I also tried using `.astype()` to convert to an int:

answer.astype(int,casting='same_kind'))

but I get:

TypeError: Cannot cast array data from dtype('float64') to dtype('int32') according to the rule 'same_kind'

I am sure importing the ceiling/floor function from `math` would solve this, but I am aware that some results may end up being normal decimals of maybe 4dp, rather than .999999 or .111111 recurring, so rounding isn't the best option

Any advice on the best way of converting?

🌐
NumPy
numpy.org › doc › 2.1 › user › basics.types.html
Data types — NumPy v2.1 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) See Specifying and constructing data types for more information about specifying and constructing data type objects, including how to specify parameters like the byte order. To convert the type of an array, use the .astype() method. For example: ... Note that, above, we could have used the Python float object as a dtype instead of numpy.float64.
🌐
Finxter
blog.finxter.com › 5-best-ways-to-convert-integer-to-float64-in-python
5 Best Ways to Convert Integer to Float64 in Python – Be on the Right Side of Change
February 18, 2024 - This is the most straightforward method and is supported across all Python versions. ... The code snippet takes an integer and passes it to the float() constructor, which converts it to a floating-point number, implicitly to float64 on 64-bit machines.
🌐
AskPython
askpython.com › home › python string to float, float to string
Python String to float, float to String - AskPython
February 16, 2023 - Python provides us with the built-in float() method to convert the data type of input from String to float.