问题:无法根据规则“安全”将数组数据从dtype('int64')强制转换为dtype('int32')。求解答 谢谢❀

讨论数量: 1
Jason990420
>>> import numpy as np
>>> a = np.array([1, 2, 3], dtype=np.int64)
>>> a.astype(np.int32, casting='unsafe')
array([1, 2, 3])
>>> a.astype(np.int32, casting='safe')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'
>>> b = a/4
>>> b, b.dtype
(array([0.25, 0.5 , 0.75]), dtype('float64'))
>>> 2**32
4294967296
>>> a = np.array([4294967296, 4294967297, 4294967298], dtype=np.int64)
>>> b = a.astype(np.int32, casting='unsafe')
>>> a.astype(np.int32, casting='unsafe')
array([0, 1, 2])
>>> a.astype(np.int32, casting='safe')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'

casting {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur. Defaults to 'unsafe' for backwards compatibility.

  • 'no' means the data types should not be cast at all.
  • 'equiv' means only byte-order changes are allowed.
  • 'safe' means only casts which can preserve values are allowed.
  • 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed.
  • 'unsafe' means any data conversions may be done.
4周前 评论
chenmeiying (楼主) 2周前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!