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().

Answer from Warren Weckesser on Stack Overflow
Top answer
1 of 3
32

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]
Discussions

unable to change from object type to float64 in pandas - Stack Overflow
I am looking forward to groupby the columns in a df and I had to look to this post pandas groupby dropping columns because in my case I am also loosing columns when group_by().mean() and I tried to... More on stackoverflow.com
🌐 stackoverflow.com
BUG: cannot safely cast non-equivalent float64 to Int64
BugNeeds TriageIssue that has not ... that has not been reviewed by a pandas team member ... import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(3,4), columns= list('ABCD')) df_int = pd.to_numeric(df['A'], errors='coerce').astype('Int64') cannot safely cast non-equivalent float64 to Int64, it should happen like when you convert from float64 to int64, which is rounding down ... More on github.com
🌐 github.com
13
October 26, 2020
BUG: Weird conversion behavior from np.float32 to Python float
Specifically, there are two different things going on in the two different statements. But in both statements, the 5.1 on the LHS is first being converted to np.float32 and then converted back up to np.float64. More on github.com
🌐 github.com
February 16, 2024
TypeError: Cannot convert a MPS Tensor to float64 dtype as the MPS framework doesn't support float64. Please use float32 instead
I’m trying to run the most basic example of the trl package: # imports import torch from transformers import AutoTokenizer from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead, create_reference_model from trl.core import respond_to_batch # get models model = ... More on discuss.huggingface.co
🌐 discuss.huggingface.co
0
0
June 11, 2023
🌐
GitHub
github.com › numpy › numpy › issues › 21906
`np.float64` is not accepted as `float` under static type checks · Issue #21906 · numpy/numpy
July 2, 2022 - However, this fact does not seem to be exposed by the numpy type stubs. # Python version 3.8.10, numpy version 1.23.0 import numpy as np x = np.float64(1.0) print(f"x={x} of type={type(x)} is float: {isinstance(x, float)}") # x=1.0 of type=<class 'numpy.float64'> is float: True def f(a: float) -> float: return a f(x) """ pyright 1.1.256: error: Argument of type "float64" cannot be assigned to parameter "a" of type "float" in function "f" "float64" is incompatible with "float" (reportGeneralTypeIssues) mypy 0.961: error: Argument 1 to "f" has incompatible type "floating[_64Bit]"; expected "float" """
Author: numpy
🌐
YourBasic
yourbasic.org › golang › convert-string-to-float
Convert between float and string · YourBasic Go
Use the strconv.ParseFloat function to parse a string as a floating-point number with the precision specified by bitSize: 32 for float32, or 64 for float64. func ParseFloat(s string, bitSize int) (float64, error) When bitSize is 32, the result still has type float64, but it will be convertible to float32 without changing its value.
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › convert-pandas-dataframe-column-to-float
Convert Pandas Dataframe Column To Float - GeeksforGeeks
July 23, 2025 - Original DataFrame Column1 Column2 0 10.5 15.3 1 20.7 25.6 2 30.2 35.8 3 xyz Data types after conversion: Column1 float64 Column2 float64 dtype: object DataFrame after conversion: Column1 Column2 0 10.5 15.3 1 20.7 25.6 2 30.2 35.8 3 NaN NaN · We can convert multiple columns to float in the dataframe by passing multiple columns while conversion.
🌐
GitHub
github.com › pandas-dev › pandas › issues › 37429
BUG: cannot safely cast non-equivalent float64 to Int64 · Issue #37429 · pandas-dev/pandas
October 26, 2020 - TypeError: cannot safely cast non-equivalent float64 to int64 ... Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment ... BugNeeds TriageIssue that has not been reviewed by a pandas team memberIssue that has not been reviewed by a pandas team member
Author: pandas-dev
🌐
GitHub
github.com › numpy › numpy › issues › 25836
BUG: Weird conversion behavior from np.float32 to Python float · Issue #25836 · numpy/numpy
February 16, 2024 - The biggest precision wins, so the LHS gets cast up to np.float64 before doing the comparison; you are implicitly requesting the cast up to np.float64 by using a float object on the RHS. O OTOH, if you used a np.float32 scalar on the RHS, you would have gotten the desired comparison. >>> np.array(5.1, dtype=np.float32) == np.float32(5.1) True · >>> type(np.array(5.1, dtype=np.float32).item()) float · ndarray.item() converts scalars to proper Python builtin types, in this case float (which corresponds to np.float64), so you are more or less explicitly requesting the cast up to np.float64.
Find elsewhere
🌐
Hugging Face
discuss.huggingface.co › 🤗transformers
TypeError: Cannot convert a MPS Tensor to float64 dtype as the MPS framework doesn't support float64. Please use float32 instead - 🤗Transformers - Hugging Face Forums
June 11, 2023 - I’m trying to run the most basic example of the trl package: # imports import torch from transformers import AutoTokenizer from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead, create_reference_model from trl.core import respond_to_batch # get models model = ...
Top answer
1 of 7
49

You can convert most of the columns by just calling convert_objects:

In [36]:

df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[36]:
Date         object
WD            int64
Manpower    float64
2nd          object
CTR          object
2ndU        float64
T1            int64
T2          int64
T3           int64
T4        float64
dtype: object

For column '2nd' and 'CTR' we can call the vectorised str methods to replace the thousands separator and remove the '%' sign and then astype to convert:

In [39]:

df['2nd'] = df['2nd'].str.replace(',','').astype(int)
df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
df.dtypes
Out[39]:
Date         object
WD            int64
Manpower    float64
2nd           int32
CTR         float64
2ndU        float64
T1            int64
T2            int64
T3            int64
T4           object
dtype: object
In [40]:

df.head()
Out[40]:
        Date  WD  Manpower   2nd   CTR  2ndU   T1    T2   T3     T4
0   2013/4/6   6       NaN  2645  5.27  0.29  407   533  454    368
1   2013/4/7   7       NaN  2118  5.89  0.31  257   659  583    369
2  2013/4/13   6       NaN  2470  5.38  0.29  354   531  473    383
3  2013/4/14   7       NaN  2033  6.77  0.37  396   748  681    458
4  2013/4/20   6       NaN  2690  5.38  0.29  361   528  541    381

Or you can do the string handling operations above without the call to astype and then call convert_objects to convert everything in one go.

UPDATE

Since version 0.17.0 convert_objects is deprecated and there isn't a top-level function to do this so you need to do:

df.apply(lambda col:pd.to_numeric(col, errors='coerce'))

See the docs and this related question: pandas: to_numeric for multiple columns

2 of 7
41

convert_objects is deprecated.

For pandas >= 0.17.0, use pd.to_numeric

df["2nd"] = pd.to_numeric(df["2nd"])
🌐
Reddit
reddit.com › r/julia › error: cannot `convert` an object of type vector{int64} to an object of type float64
r/Julia on Reddit: Error: Cannot `convert` an object of type Vector{Int64} to an object of type Float64
November 1, 2021 -

Hi! I was wondering if anyone could help me with this error? I will paste the code below:

using JuMP, Cbc a3 = Model(with_optimizer(Cbc.Optimizer, LogLevel = 0))

@variable(a3, x_1 >= 0) @variable(a3, y_1 >= [0,1], Int) #the y_i are binary variables @variable(a3, y_2 >= [0,1], Int) @variable(a3, y_3 >= [0,1], Int)

@constraint(a3, x_1 + y_1 + y_2 + y_3 >= 2) @constraint(a3, 10x_1 + 5y_1 + 3y_2 + 4y_3 <= 2)

@objective(a3, Min, 2x_1 - 3y_1 - 2y_2 - 3y_3) optimize!(a3)

Edit: It's got identation, but the pasted code doesn't show it

🌐
Julia Programming Language
discourse.julialang.org › new to julia
Converting a Vector{float64} to float{64} - New to Julia - Julia Programming Language
April 24, 2022 - I have a one element vector{float64} called “Ge” that operates inside of a for loop. The code I am trying to do is result[num] = (part1+part2)/Ge in which both part 1 and part 2 are type Float64. It doesn’t let me do this because Julia doesn’t allow mathematical operations between Float64 and Vector{float64}. How can I convert any of these variables to make this math operation work?
🌐
Julia Programming Language
discourse.julialang.org › general usage
MethodError: Cannot `convert` an object of type Vector{Float64} to an object of type Float64 - General Usage - Julia Programming Language
August 13, 2021 - What does this error mean? That an object somewhere in the code is specified as Vector{Float64} and Julia cannot convert it to Float64? I thought it didn’t matter so long as the type was matched (i.e. both Float64).
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.

🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.to_numeric.html
pandas.to_numeric — pandas 3.0.6 documentation - PyData |
For non-numeric inputs, the default return dtype is float64 or int64 depending on the data supplied. Use the downcast parameter to obtain other dtypes. Please note that precision loss may occur if really large numbers are passed in. Due to the internal limitations of ndarray, if numbers smaller than -9223372036854775808 (np.iinfo(np.int64).min) or larger than 18446744073709551615 (np.iinfo(np.uint64).max) are passed in, it is very likely they will be converted to float so that they can be stored in an ndarray.
🌐
Pandas
pandas.pydata.org › pandas-docs › stable › reference › api › pandas.to_numeric.html
pandas.to_numeric — pandas 3.0.2 documentation - PyData |
For non-numeric inputs, the default return dtype is float64 or int64 depending on the data supplied. Use the downcast parameter to obtain other dtypes. Please note that precision loss may occur if really large numbers are passed in. Due to the internal limitations of ndarray, if numbers smaller than -9223372036854775808 (np.iinfo(np.int64).min) or larger than 18446744073709551615 (np.iinfo(np.uint64).max) are passed in, it is very likely they will be converted to float so that they can be stored in an ndarray.
🌐
Reddit
reddit.com › r/golang › is there an easy way to check if an any-value can convert to float64?
r/golang on Reddit: Is there an easy way to check if an any-value can convert to float64?
February 2, 2026 -

I have a number from JavaScript. By definition, JavaScript numbers are floating point, but the JS engine may optimize this when the actual value doesn't have a fractional part.

Sobek (a fork of Goja) returns an int64. But then theoretically it could also be 32, 16, or 8 bit integers, signed/unsigned.

func (v value) Number() float64 {
	val := v.value.Export() // Get the native sobek value

	if res, ok := val.(float64); ok {
		return res
	}
	if res, ok := val.(int64); ok {
		return float64(res)
	}
	if res, ok := val.(uint64); ok {
		return float64(res)
	}
	if res, ok := val.(int32); ok {
		return float64(res)
	}
	if res, ok := val.(uint32); ok {
		return float64(res)
	}
	// ... and more
	return 0.0
}

Is there a way to simplify this?

🌐
GitHub
github.com › pythonnet › pythonnet › issues › 1936
failure to convert numpy.float64 into System.Double · Issue #1936 · pythonnet/pythonnet
September 12, 2022 - python code: test_array = np.array([123, 345], np.float) CSharpClass.Test(test_array) C# code public static void Test(double[] TestData) {...} I already have a fix for this issue. ... internal static bool PyFloat_Check(BorrowedReference ob) { return PyObject_TypeCheck(ob, PyFloatType); //return PyObject_TYPE(ob) == PyFloatType; // existing code } This will convert any type that is derived from PyFloatType, which includes numpy.float64
Author: pythonnet
🌐
Stack Overflow
stackoverflow.com › questions › 78625587 › fail-to-convert-float-64-to-float-32-in-python
pandas - Fail to convert float 64 to float 32 in python - Stack Overflow
Copycol1 float64 col2 float64 dtype: object col1 float64 col2 float64 dtype: object tensor([3.1000], dtype=torch.float64) I tried to use both method provided by pandas and pytorch. Although it does not raise any errors, it does not work. And I cannot put it into neural network layers as it requires float 32 data type. I also tried to convert them to int, int64, int32 using both method.