如何使用numpy.ndarray.astype将dtype“对象”的NumPy数组安全地转换为“ str”?

时间:2020-02-26 17:46:36

标签: python numpy casting

不确定为什么会出现以下错误。这只是一个例子。长话短说,我正在处理dtype'object'的numpy数组,并且想对其中的一些整数进行“字符串化”以写入文件。因此,我使用了.astype(str)方法,但随后它截断了一些我想添加到数组中的新字符串,这促使我决定始终要使用dtype ='object'。因此,我想执行x.astype('str')。astype('object'),以便随后添加更多字符串而不会被截断。

但是我想在使用NumPy astype函数时保持安全,所以我想始终使用casting ='safe'。但是由于某种原因它会出错,为什么会这样呢?

TypeError:无法根据规则“安全”将数组从dtype('O')转换为dtype('U')

为什么在cast ='safe'时会给出错误,但是让cast为起作用的默认值(“ unsafe”)?

In [1]: import numpy as np                                                      

In [2]: x = [['abc']]                                                           

In [3]: x = np.array(x, dtype = 'object')                                       

In [4]: x                                                                       
Out[4]: array([['abc']], dtype=object)

In [5]: x.astype('str', casting = 'safe')                                       
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-e036b3323cdf> in <module>
----> 1 x.astype('str', casting = 'safe')

TypeError: Cannot cast array from dtype('O') to dtype('<U') according to the rule 'safe'

In [6]: x.astype('str')                                                         
Out[6]: array([['abc']], dtype='<U3')

In [7]:    

0 个答案:

没有答案