Ndarray的数据类型
Dtype(数据类型)是一个特殊的对象,它含有ndarray将一块内存解释为特定数据类型所需的信息
示例:
arr1 = np.array([1, 2, 3], dtype=np.float64)
arr2 = np.array([1, 2, 3], dtype=np.int32)
arr1
Out[32]: array([1., 2., 3.])
arr2
Out[33]: array([1, 2, 3])
arr1.dtype
Out[34]: dtype('float64')
arr2.dtype
Out[35]: dtype('int32')
可以通过ndarry的astype方法显示地转换其dtype
示例1:整数转为浮点
arr = np.array([1, 2, 3, 4, 5])
arr.dtype
Out[37]: dtype('int32')
float_arr = arr.astype(np.float32)
float_arr.dtype
Out[39]: dtype('float32')
示例2:浮点转为整数
arr = np.array([3.7, -1.2, -2.6, 0.5, 12,9, 10.1])
arr
Out[44]: array([ 3.7, -1.2, -2.6, 0.5, 12. , 9. , 10.1])
arr.astype(np.int32)
Out[45]: array([ 3, -1, -2, 0, 12, 9, 10])
示例3:字符串转为数字
str1 = np.array(['12.5', '-9.6', '42'], dtype=np.string_)
str1
Out[52]: array([b'12.5', b'-9.6', b'42'], dtype='|S4')
str1.astype(float)
Out[53]: array([12.5, -9.6, 42. ])
示例4:另外一个用法: 使用另一个数组的数据类型
int_arr = np.arange(10)
cal = np.array([.22, .270, .357, .389, .44 , .50],dtype=np.float64)
int_arr.astype(cal.dtype)
Out[56]: array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
示例5:简洁的类型代码来表示dtype
emtpy_unit32 = np.empty(8, dtype='u4')
emtpy_unit32
Out[58]:
array([0, 1075314688, 0, 1075707904, 0,1075838976, 0, 1072693248], dtype=uint32)
注意:调用astype无论如何都会创建一个新的数组(原始数据的一份copy),即使新dtype跟老dtype相同也是如此