Srikanth
Srikanth

Reputation: 829

python: converting an numpy array data type from int64 to int

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. This array will later be used as an input in a function defined in ABAQUS. The problem is to do with the data type of the integers. In the array, the integers have data type 'int64'. However, I am getting the following error when I input the array to the desired function:

"Only INT, FLOAT and DOUBLE supported by the ABAQUS interface (use multiarray with typecode int if standard long is 64 bit)"

I do not need assistance with ABAQUS. If i convert the data type to 'int' in python, that would suffice. I thought that I could simply use the int() function to convert the data type. This did not work. Any suggestions will be highly appreciated. Thank you all.

Upvotes: 39

Views: 137168

Answers (5)

bardia rafieian
bardia rafieian

Reputation: 1

In the end, if you convert an list of int64 values to int with numpy, you will have a numpy value (int64, int32, etc). In case you want a regular int (not numpy int), I found a way which is working. You will convert it to string, and then convert to list! enjoy...

import ast

a = ast.literal_eval(str(a))

Upvotes: 0

bigonazzi
bigonazzi

Reputation: 834

numpy.ndarray.tolist will do it:

a.tolist()

If your data is a pandas series you can call their tolist wrapper with the same result.

Upvotes: 41

Charles q
Charles q

Reputation: 29

If it's a pandas serise, you can first convert it to Dataframe, then use df.to_dict(), then the numpy.int64 will convert to int

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: df = pd.DataFrame(np.random.randint(5,size=(3,4)),
index=np.arange(3))

In [4]: type(df[0][0])

Out[4]: numpy.int64

In [5]: dict_of_df = df.to_dict()

In [6]: type(dict_of_df[0][0])

Out[6]: int

Upvotes: -6

Frank Freeman
Frank Freeman

Reputation: 31

Use the item() method for numpy.int64 object, as Mike T's answer in another similar question explained.

Official documentation is here: https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.chararray.item.html#numpy.chararray.item

Upvotes: 3

Srikanth
Srikanth

Reputation: 829

@J.F. Sebastian's answer:

a.astype(numpy.int32)

Upvotes: 27

Related Questions