初始化numpy数据:
import numpy as np
a = np.random.random(4)
print(a)
# array([ 0.0945377 , 0.52199916, 0.62490646, 0.21260126])
print(a.dtype)
# float64
print(a.shape)
# (4,)
改变dtype:
a.dtype = 'float32'
print(a)
# array([ 3.65532693e+20, 1.43907535e+00, -3.31994873e-25,
# 1.75549972e+00, -2.75686653e+14, 1.78122652e+00,
# -1.03207532e-19, 1.58760118e+00], dtype=float32)
print(a.shape)
# (8,)
发现改变了数据dtype后,数组的长度也发生了变化
b = np.array([1., 2., 3., 4.])
print(b.dtype)
# dtype('float64')
c = b.astype(int)
print(c)
# array([1, 2, 3, 4])
print(c.shape)
# (8,)
print(c.dtype)
# dtype('int32')
发现使用astype()改变数据类型,不会出现数组长度变化的情况
numpy中的数据类型转换,不能直接改原数据的dtype,只能用函数astype()
float默认为float64,int默认为int32
参考:https://www.cnblogs.com/hhh5460/p/5129032.html