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.
🌐
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 ...
🌐
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 dtype parameter.
🌐
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 › 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. ... import numpy as np x = np.float32(1.9) x.tolist() # 1.899999976158142 x.item() # 1.899999976158142 x.view() # 1.9 str(x) # '1.9' float(str(x)) # 1.9
Author   ringsaturn
🌐
NumPy
numpy.org › doc › stable › user › basics.types.html
Data types — NumPy v2.4 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.
🌐
GitHub
github.com › numpy › numpy › issues › 25836
BUG: Weird conversion behavior from np.float32 to Python float · Issue #25836 · numpy/numpy
February 16, 2024 - Describe the issue: I found out that converting np.float32 to a Python float via .item() gives a weird result. While I understand NumPy retains the float32 internal representation of the value, I feel that for such a simple value the fol...
Author   fandreuz
Find elsewhere
🌐
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.
🌐
GitHub
github.com › numpy › numpy › issues › 22618
Question: numpy.float32 produces wrong conversion of certain integer values · Issue #22618 · numpy/numpy
August 24, 2022 - The issue also extends to applications in pycuda. import numpy as np # Produces equivalent values i=16777342 print(int(i)) print(float(i)) print(np.float32(i)) print(np.float64(i)) print() # Does not produce equivalent values i=16777343 print(int(i)) print(float(i)) print(np.float32(i)) print(np.float64(i)) print() # Produces equivalent values i=16777344 print(int(i)) print(float(i)) print(np.float32(i)) print(np.float64(i)) print() # Does not produce equivalent values i=16777345 print(int(i)) print(float(i)) print(np.float32(i)) print(np.float64(i)) print() # Does not produce equivalent values i=181567487 print(int(i)) print(float(i)) print(np.float32(i)) print(np.float64(i))
Author   SilentAndromeda
🌐
Vultr Docs
docs.vultr.com › python › third-party › numpy › array › astype
Python Numpy array astype() - Convert Data Type | Vultr Docs
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) Explain Code
🌐
Snyk
snyk.io › advisor › numpy › functions › numpy.float32
How to use the numpy.float32 function in numpy | Snyk
def get_dummy_encoder_output(encoder_out_shape=(100, 80, 5)): """ This only provides an example to generate dummy encoder output """ (T, B, D) = encoder_out_shape encoder_out = {} encoder_out["encoder_out"] = torch.from_numpy( np.random.randn(*encoder_out_shape).astype(np.float32) ) seq_lengths = torch.from_numpy(np.random.randint(low=1, high=T, size=B)) # some dummy mask encoder_out["encoder_padding_mask"] = torch.arange(T).view(1, T).expand( B, -1 ) >= seq_lengths.view(B, 1).expand(-1, T) encoder_out["encoder_padding_mask"].t_() # encoer_padding_mask is (T, B) tensor, with (t, b)-th element indicate # whether encoder_out[t, b] is valid (=0) or not (=1) return encoder_out ·
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.

🌐
NumPy
numpy.org › devdocs › user › basics.types.html
Data types — NumPy v2.5.dev0 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.
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.

🌐
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....