Python 将 dtype 从 int64 转换为 int32

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22725043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:29:42  来源:igfitidea点击:

Convert dtype from int64 to int32

pythonnumpy

提问by valentin

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).

基本上,我使用 python x32 位从文件加载包含多个 numpy 数组的列表对象(以前使用 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.

如何将列表中的数组元素类型转换为 int32,以便我可以将它们与 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

看看里面的东西 data['Y']在此处输入图片说明

采纳答案by jterrace

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 astypefunction:

正如其他人所说,32 位版本的 numpy 仍然支持 64 位 dtype。但是如果你真的需要转换成int32,你可以使用astype函数:

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