浮点型之间转换

numpy整型默认float32,不能直接更改类型,否则数组长度会变化

import numpy as np
x = np.random.rand(4)
print(x)
print(x.dtype)
print(x.shape)

结果

[0.45807523 0.62492706 0.85296223 0.58924266]
float64
(4,)
x1 = np.random.rand(4)
x1.dtype = np.float32
print(x1)
print(x1.dtype)
print(x1.shape)

结果

[ 1.4401711e+06  1.8517824e+00  1.9937775e+29  1.7320998e+00
 -3.3461947e-05  1.6896042e+00  2.1652360e-05  1.8127537e+00]
float32
(8,)

numpy整型默认float32,不能直接更改类型,否则数组长度会变化

y = np.array([1,2,3,4])
print(y.dtype)
print(y.shape)

结果

int32
(4,)
y.dtype = np.int16
print(y)
print(y.shape)

结果

[1 0 2 0 3 0 4 0]
(8,)

使用astype()

import numpy as np
x = np.random.rand(4).astype(np.float32)
print(x)
print(x.dtype)
print(x.shape)

结果

[0.5974177  0.46573412 0.8508142  0.29241505]
float32
(4,)