Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dtype from int64 to int32

Tags:

Basically, I am using python x32 bit to load from file a list object containing several numpy arrays (previously saved inside a pickle using python x64).

I can load them properly and check the contents but I cannot use them.

TypeError: Cannot cast array data from dtype('int64') to dtype('int32') 

How can I convert the arrays element type from within the list to int32 so I can use them with python x32.

The error comes when I try to execute the following part:

a=np.bincount(np.hstack(data['Y'])) 

Looking at what is inside data['Y'] enter image description here

like image 929
valentin Avatar asked Mar 28 '14 23:03

valentin


People also ask

What is Int32 and Int64 in Python?

Int32 is used to represents 32-bit signed integers . Int64 is used to represents 64-bit signed integers. 2. Int16 stands for signed integer. Int32 also stands for signed integer.

What is Dtype Int32?

int32 is an integer between -2^31 and 2^31 - 1. This range requires 32 bits of memory, and hence the name. Numpy allows for a variety of data types that are not present in regular Python, whose int type can be really, really large. Moreover, unlike Python's list, all elements of a Numpy array must be of the same type.

How do you convert an object to int in Python?

Convert Column to int (Integer)Use pandas DataFrame. astype() function to convert column to int (integer), you can apply this on a specific column or on an entire DataFrame. To cast the data type to 64-bit signed integer, you can use numpy. int64 , numpy.


1 Answers

As others have said, 32-bit versions of numpy still support 64-bit dtypes. But if you really need to convert to int32, you can use the astype function:

>>> import numpy as np >>> x = np.array([1,2,3], dtype=np.int64) >>> x array([1, 2, 3]) >>> x.dtype dtype('int64') >>> y = x.astype(np.int32) >>> y array([1, 2, 3], dtype=int32) 
like image 142
jterrace Avatar answered Sep 21 '22 10:09

jterrace