移位数组时出现类型错误

问题描述

尝试使用 numpy 右移数组时出现错误

代码如下:

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 方法不能就地操作,因为它在一般情况下将元素转换为不同的大小。浮点数通常是 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