ShanZhengYang
ShanZhengYang

Reputation: 17651

How to convert python int into numpy.int64?

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

Upvotes: 33

Views: 150015

Answers (3)

Jebeh Kawah
Jebeh Kawah

Reputation: 21

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'})

Upvotes: 2

user2357112
user2357112

Reputation: 281843

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.

Upvotes: 50

sascha
sascha

Reputation: 33542

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.

Upvotes: 12

Related Questions