Hen*_*ton 8 python arrays types casting numpy
将一个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'
Run Code Online (Sandbox Code Playgroud)
在处理需要指定索引或长度的NumPy函数时,这是很常见的(不仅仅是这样take
,请参见此处).
问题在于,为了建立索引,NumPy希望将您的uint32
数组视为一个int32
数组(可能是32位系统上的"指针"整数类型np.intp
),并希望将其转换为该类型.
它无法安全地执行此操作 - 无符号数组中的某些整数可能无法表示为带符号的32位整数.您看到的错误反映了这一点.
这意味着如果b
有dtype int64
或float dtype,你会得到相同的错误,但如果它是int32
一个或更小的整数dtype 则不会.
对于它的价值,这对于a[b]
允许不安全的转换的索引符号来说不是一个直接的问题(但如果索引超出界限则会引发错误).试试例子a[2**31]
- NumPy转换为int32
但后来抱怨索引-2147483648
超出范围.