当numpy int32数组转换为float32时,值会更改

时间:2018-12-03 16:52:44

标签: python arrays python-3.x numpy multidimensional-array

我通过data_np将numpy数组data_np.dtype = np.float32的类型从int32更改为float32 但是它正在改变 enter image description here

enter image description here

,并在两者之间添加一个附加的0列。 有关如何正确执行此操作的任何建议。

1 个答案:

答案 0 :(得分:1)

ndarray.dtype并不意味着修改dtype。我会使用astype

data_np = data_np.astype(np.float32)

示例

data_np = np.random.randint(0,10,(3,3),dtype=np.int32)
>>> data_np
array([[7, 8, 4],
       [7, 6, 8],
       [4, 5, 9]], dtype=int32)

data_np = data_np.astype(np.float32)
>>> data_np
array([[7., 8., 4.],
       [7., 6., 8.],
       [4., 5., 9.]], dtype=float32)