numpy数组强制转换不安全 [英] numpy array casting ruled not 'safe'

查看:122
本文介绍了numpy数组强制转换不安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用另一个索引一个numpy数组-两者都定义为dtype ='uint32'.使用numpy.take进行索引并获得不安全的转换错误.之前没有碰到过.知道发生了什么吗?

Indexing one numpy array with another - both are defined as dtype='uint32'. Using numpy.take to index and get an unsafe casting error. Not come across this before. Any idea what is going on?

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'

推荐答案

在工作需要指定索引或长度的NumPy函数时,这很常见(不仅是take,例如请参见

This is quite common when working NumPy functions that require indexes or lengths to be specified (it's not just take, see for example here).

问题是,出于索引目的,NumPy希望将您的uint32数组视为int32数组(这可能是您的32位系统上的指针"整数类型,

The problem is that, for indexing purposes, NumPy would like to treat your uint32 array as an int32 array (which is probably the "pointer" integer type on your 32 bit system, np.intp) and wants to cast it down to that type.

它不能安全地执行此操作-无符号数组中的某些整数可能无法表示为有符号的32位整数.您看到的错误反映了这一点.

It can't do this safely - some of the integers in an unsigned array might not be representable as a signed 32 bit integer. The error you see reflects this.

这意味着,如果b具有dtype int64或float dtype,您将得到相同的错误,但如果它是int32或更小的整数dtype,则不会得到相同的错误.

This means that you'll get the same error if b has dtype int64 or a float dtype, but not if it is int32 or a smaller integer dtype.

就其价值而言,对于索引表示法a[b]而言,这不是一个直接的问题,它允许不安全的转换(但如果索引超出范围,则会引发错误).例如,尝试a[2**31]-NumPy强制转换为int32,但随后抱怨索引-2147483648超出范围.

For what it's worth, this isn't an immediate problem for the indexing notation a[b] which allows the unsafe casting (but will raise an error if the index is out of bounds). Try for example a[2**31] - NumPy casts to int32 but then complains that the index -2147483648 is out of bounds.

这篇关于numpy数组强制转换不安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆