我正在尝试转换 3D 数组中列的浮点值:
for i in range(timeseries_resampled.shape[0]):
timeseries_resampled[i, :, 9] = (np.rint(timeseries_resampled[i, :, 9])).astype(int)
print(timeseries_resampled[i, :, 9].dtype) # float64
print(timeseries_resampled[i, :, 9].astype(int).dtype) # int64
为什么
for
循环的第一个赋值不起作用。我不太确定为什么它不起作用。我也尝试设置copy=False
但没有任何效果。
举个例子:
a = np.zeros((2, 3, 4))
for i in range(a.shape[0]):
a[i, :, 3] = a[i, :, 3].astype(int)
print(a[i, :, 3])
print(a[i, :, 3].astype(int))
带输出
[0. 0. 0.]
[0 0 0]
[0. 0. 0.]
[0 0 0]
so
a[i, :, 3]
仅包含浮点值,而 a[i, :, 3].astype(int)
仅包含 int 值。那么为什么是作业
a[i, :, 3] = a[i, :, 3].astype(int)
不工作?我希望
a[i, :, 3]
现在只包含 int 值。
dtype
是数组本身的属性,而不是添加到数组的值。 timeseries_resampled
的 dtype
为 float64
,因此无论您放入数组中的任何值都将在赋值时从它们可能具有的任何类型转换为 float64
。
我不确定为什么它没有转换为
int
,如果有效,您可以试试这个:
np.rint(timeseries_resampled[i, :, 9]).astype(np.int32)
#astype creates a copy, so it may be not the most efficient memory operation