z_as_int64 = numpy.int64(z)

It's that simple. Make sure you have a good reason, though - there are a few good reasons to do this, but most of the time, you can just use a regular int directly.

Answer from user2357112 on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how to convert python int into numpy.int64?
r/learnpython on Reddit: How to convert python int into numpy.int64?
October 11, 2017 -

Given a variable in python of type int, e.g.

z = 50
type(z) 
## outputs <class 'int'>

is there a straightforward way to convert this variable into numpy.int64?

It appears one would have to convert this variable into a numpy array, and then convert this into int64. That feels quite convoluted.

https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html

Discussions

python: converting an numpy array data type from int64 to int - Stack Overflow
I am somewhat new to python and I am using python modules in another program (ABAQUS). The question, however, is completely python related. In the program, I need to create an array of integers. T... More on stackoverflow.com
🌐 stackoverflow.com
Converting numpy dtypes to native python types - Stack Overflow
If I have a numpy dtype, how do I automatically convert it to its closest python data type? For example, numpy.float32 -> "python float" numpy.float64 -> "python float" numpy.uint32 -> " More on stackoverflow.com
🌐 stackoverflow.com
Preventing numpy from converting float type to numpy.int64 type
Numpy arrays have a defined data type. eta_hat is an array of dtype int64, because that's how you initialized it in the first place: as the docs say, if no type is given explicitly then "the type will be determined as the minimum type required to hold the objects in the sequence". More on reddit.com
🌐 r/learnpython
3
1
April 3, 2023
python - Convert ndarray from float64 to integer - Stack Overflow
Note that passing int as dtype to astype or array will default to a default integer type that depends on your platform. For example on Windows it will be int32, on 64bit Linux with 64bit Python it's int64. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
NumPy
numpy.org › doc › stable › user › basics.types.html
Data types — NumPy v2.4 Manual
The data type can also be used indirectly to query properties of the type, such as whether it is an integer: >>> d = np.dtype(np.int64) >>> d dtype('int64') >>> np.issubdtype(d, np.integer) True >>> np.issubdtype(d, np.floating) False · To convert the type of an array, use the .astype() method.
🌐
Google Groups
groups.google.com › g › numpy › c › 6nCcuw3NkKw
[Numpy-discussion] PyInt and Numpy's int64 conversion
I want to convert a numpy array of integers (whose elements are numpy's 'int64') The problem is that it this int64 type is not compatible with the standard python integer type: I cannot use PyInt_Check, and PyInt_AsUnsignedLongMask to check and convert from int64: basically PyInt_Check returns ...
🌐
Saturn Cloud
saturncloud.io › blog › converting-python-int-to-numpyint64-a-comprehensive-guide
Converting Python int to numpy.int64: A Guide | Saturn Cloud Blog
October 4, 2023 - On the other hand, numpy.int64 is a fixed-size integer type that can store integers from -9223372036854775808 to 9223372036854775807. It is more memory-efficient and faster for operations on large arrays of data, making it a preferred choice for data-intensive tasks. Now, let’s get to the main part of our discussion - converting ...
🌐
NumPy
numpy.org › doc › 2.1 › user › basics.types.html
Data types — NumPy v2.1 Manual
To determine the type of an array, look at the dtype attribute: ... dtype objects also contain information about the type, such as its bit-width and its byte-order. The data type can also be used indirectly to query properties of the type, such as whether it is an integer: >>> d = np.dtype(np.int64...
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.

Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › preventing numpy from converting float type to numpy.int64 type
r/learnpython on Reddit: Preventing numpy from converting float type to numpy.int64 type
April 3, 2023 - I also have a class attribute eta_hat which is initialized as numpy.array( [ [0], [0], [0] ] ), the idea it being a column vector. My goal is to make the values of eta_hat the values of eta. However, the piece of code · self.eta_hat[0][0], self.eta_hat[1][0], self.eta_hat[2][0] = eta[0], eta[1], eta[2] converts eta[x] from float to numpy.int64 in self.eta_hat[x][0]. I do not understand how numpy handles these, and would love an explenation on how I could fix this problem.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.4 Manual
June 22, 2021 - Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order. ... When casting from complex to float or int.
🌐
NumPy
numpy.org › devdocs › user › basics.types.html
Data types — NumPy v2.5.dev0 Manual
The data type can also be used indirectly to query properties of the type, such as whether it is an integer: >>> d = np.dtype(np.int64) >>> d dtype('int64') >>> np.issubdtype(d, np.integer) True >>> np.issubdtype(d, np.floating) False · To convert the type of an array, use the .astype() method.
🌐
Python Forum
python-forum.io › thread-42567.html
System showing np.int64(xxx) as output
I was using Numpy and try to find the number in an array which is the closest to the number 57. I write the following code. a = np.array([78,22,65,87,12,98,63,79]) x = 57 a[np.argmin(np.abs(a - x))]The output I get is Output:np.int64(63) instead of 6...
🌐
GitHub
github.com › numpy › numpy › issues › 18557
numpy converts to float if given a list of numpy.uint64 mixed with python ints · Issue #18557 · numpy/numpy
March 5, 2021 - Which results in a loss of information, since values are not exactly representable by float64. import numpy as np def print_array(a): print(a.dtype, a) large = 2**63 - 1 print_array(np.array([-1, large])) print_array(np.array([-1, np.int64(large)])) ...
Author   maxnoe
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: astype() to change dtype of an array | note.nkmk.me
February 4, 2024 - a_int[0] = 10.9 a_int[1] = -20.9 print(a_int) # [ 10 -20 3] print(a_int.dtype) # int64 · source: numpy_implicit_type_conversion.py · Python · NumPy · NumPy: Delete rows/columns from an array with np.delete() Convert between NumPy array and Python list · NumPy: reshape() to change the shape of an array ·
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.1 Manual
Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order. ... When casting from complex to float or int.
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.5.dev0 Manual
Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order. ... When casting from complex to float or int.
🌐
NumPy
numpy.org › devdocs › user › basics.creation.html
Array creation — NumPy v2.5.dev0 Manual
Notice when you perform operations ... dtype, NumPy will assign a new type that satisfies all of the array elements involved in the computation, here uint32 and int32 can both be represented in as int64....
🌐
NumPy
numpy.org › doc › 2.0 › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.0 Manual
Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order. ... When casting from complex to float or int.