欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Numpy数据类型转换astype,dtype的方法

程序员文章站 2023-11-06 10:34:40
1、查看数据类型 in [11]: arr = np.array([1,2,3,4,5]) in [12]: arr out[12]: array([1, 2...

1、查看数据类型

in [11]: arr = np.array([1,2,3,4,5])
in [12]: arr
out[12]: array([1, 2, 3, 4, 5])
// 该命令查看数据类型
in [13]: arr.dtype
out[13]: dtype('int64')
in [14]: float_arr = arr.astype(np.float64)
// 该命令查看数据类型
in [15]: float_arr.dtype
out[15]: dtype('float64')

2、转换数据类型

// 如果将浮点数转换为整数,则小数部分会被截断
in [7]: arr2 = np.array([1.1, 2.2, 3.3, 4.4, 5.3221])
in [8]: arr2
out[8]: array([ 1.1 , 2.2 , 3.3 , 4.4 , 5.3221])
// 查看当前数据类型
in [9]: arr2.dtype
out[9]: dtype('float64')
// 转换数据类型 float -> int
in [10]: arr2.astype(np.int32)
out[10]: array([1, 2, 3, 4, 5], dtype=int32)

3、字符串数组转换为数值型

in [4]: numeric_strings = np.array(['1.2','2.3','3.2141'], dtype=np.string_)
in [5]: numeric_strings
out[5]: array(['1.2', '2.3', '3.2141'], dtype='|s6')
// 此处写的是float 而不是np.float64, numpy很聪明,会将python类型映射到等价的dtype上
in [6]: numeric_strings.astype(float)
out[6]: array([ 1.2, 2.3, 3.2141])

以上这篇numpy数据类型转换astype,dtype的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。