位移数组时出现类型错误
TypeError while bit shifting array
尝试使用 numpy right_shift 数组时出现错误:
代码如下:
import numpy as np
a = np.ones((10, 10)) * 64
a.astype("int16")
b = a >> 2
然后我得到
TypeError: ufunc 'right_shift' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
但根据 docs,在我看来这应该可行。
astype
方法不能就地操作,因为它在一般情况下将元素转换为不同的大小。 float一般是64位,而int16
明明是16位。
因此,a.astype("int16")
行是空操作。
你可以写成
a = a.astype("int16")
或者合并最后两行:
b = a.astype("int16") >> 2
但是,一般来说,使用 astype
是代码味道。 Numpy 提供了分配正确类型和值的数组的工具:
a = np.full((10, 10), 64, dtype=np.int16)
b = a >> 2
尝试使用 numpy right_shift 数组时出现错误:
代码如下:
import numpy as np
a = np.ones((10, 10)) * 64
a.astype("int16")
b = a >> 2
然后我得到
TypeError: ufunc 'right_shift' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
但根据 docs,在我看来这应该可行。
astype
方法不能就地操作,因为它在一般情况下将元素转换为不同的大小。 float一般是64位,而int16
明明是16位。
因此,a.astype("int16")
行是空操作。
你可以写成
a = a.astype("int16")
或者合并最后两行:
b = a.astype("int16") >> 2
但是,一般来说,使用 astype
是代码味道。 Numpy 提供了分配正确类型和值的数组的工具:
a = np.full((10, 10), 64, dtype=np.int16)
b = a >> 2