How to convert python int into numpy.int64?

Question:

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

Asked By: ShanZhengYang

||

Answers:

import numpy as np
z = 3
z = np.dtype('int64').type(z)
print(type(z))

outputs:

<class 'numpy.int64'>

But i support Juliens question in his comment.

Answered By: sascha
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.

Answered By: user2357112

For me converting to int64 was necessary for expressing a 16-digit account number as an integer without having any of its last for digits rounded off. I know using 16-digit account numbers as int instead of string is odd, but it’s the system we inherited and so the account number is either int or string, depending on where in the code you happen to be in this massive system.
Here’s how I saw it in the existing code:
df_dataframe = df_dataframe.astype({‘ACCOUNT_NUMBER’: ‘int64’})

Answered By: Jebeh Kawah
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.