【发布时间】:2015-05-05 09:34:42
【问题描述】:
用另一个索引一个 numpy 数组 - 两者都定义为 dtype='uint32'。使用 numpy.take 进行索引并获得不安全的转换错误。以前没有遇到过这个。知道发生了什么吗?
Python 2.7.8 |Anaconda 2.1.0 (32-bit)| (default, Jul 2 2014, 15:13:35) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import numpy
>>> numpy.__version__
'1.9.0'
>>> a = numpy.array([9, 7, 5, 4, 3, 1], dtype=numpy.uint32)
>>> b = numpy.array([1, 3], dtype=numpy.uint32)
>>> c = a.take(b)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
c = a.take(b)
TypeError: Cannot cast array data from dtype('uint32') to dtype('int32') according to the rule 'safe'
【问题讨论】:
-
运行 python 3.4.3 64 位和 numpy '1.9.2rc1' 时没有收到警告
-
我认为问题在于将
a.take(b)分配给c。尝试在c = a.take(b)之前设置c =numpy.array(0,dtype=numpy.uint32) -
在 Python 2.7.5 64 位和 numpy 1.9.1 中也没有警告。
-
更新到 numpy 1.9.2 但仍然是同样的错误。设置 c=numpy.array(0, dtype=numpy.uint32) 也不起作用。在 Windows 32 位 XP 和 Windows 8.1 上的结果相同。奇怪!
-
我将这个问题解释如下。 NumPy 使用有符号整数进行索引(毕竟
a[-1]的工作方式就像在 Python 列表中一样)。当它发现索引数组具有错误的 dtype 时,它会尝试将索引数组转换为有符号整数数组(如果b是一个数组,例如int16,这将是合理的并产生合理的结果)。由于这种转换对于uint32的数组是不安全的——例如,最大的uint32值将变为-1,一个相当不同的索引——NumPy 会引发错误。在使用take之前,您可能需要自己转换b的dtype。
标签: python arrays numpy types casting