Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何安全地强制转换数据类型';对象';至';str';是否使用numpy.ndarray.astype?_Python_Numpy_Casting - Fatal编程技术网

Python 如何安全地强制转换数据类型';对象';至';str';是否使用numpy.ndarray.astype?

Python 如何安全地强制转换数据类型';对象';至';str';是否使用numpy.ndarray.astype?,python,numpy,casting,Python,Numpy,Casting,不确定为什么会发生下面的错误。这只是一个例子。说来话长,我当时正在操作数据类型为“object”的numpy数组,并希望将其中的一些整数“字符串化”以写入文件。因此,我使用了.astype(str)方法,但它截断了我想添加到数组中的一些新字符串,这促使我决定始终使用dtype='object'。所以我想做x.astype('str')。astype('object'),这样我就可以添加更多的字符串,而不会截断它们 但我希望在使用NumPy astype函数时安全,所以我希望始终使用casting

不确定为什么会发生下面的错误。这只是一个例子。说来话长,我当时正在操作数据类型为“object”的numpy数组,并希望将其中的一些整数“字符串化”以写入文件。因此,我使用了.astype(str)方法,但它截断了我想添加到数组中的一些新字符串,这促使我决定始终使用dtype='object'。所以我想做x.astype('str')。astype('object'),这样我就可以添加更多的字符串,而不会截断它们

但我希望在使用NumPy astype函数时安全,所以我希望始终使用casting='safe'。但由于某种原因,它会出错,为什么会发生这种情况

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

为什么它会给出一个casting='safe'的错误,但是让casting成为默认值('safe')它会工作

[1]中的
:将numpy作为np导入
在[2]中:x=[['abc']]
在[3]中:x=np.array(x,dtype='object')
在[4]:x中
Out[4]:数组([['abc']],dtype=object)
在[5]中:x.astype('str',casting='safe')
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在里面
---->1 x.astype('str',casting='safe')

TypeError:无法将数组从dtype('O')强制转换为dtype(“你有什么版本的numpy?numpy版本1.18.1我不这么认为。如果你已经有了
对象
数据类型,并且对象更适合你的任务,为什么你要尝试转换成
str
?如果你所做的只是转换Python字符串,为什么要担心
安全
?关于“安全”的神秘之处是什么e限制性?我怀疑所有从
对象
进行的强制转换都被认为是“不安全的”。@hpaulj我正在使用的数组中还有其他类型我希望强制转换为字符串(例如int)。我担心“安全”的原因是我不希望我的字符串被截断。
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]: