当前位置: 移动技术网 > IT编程>脚本编程>Python > Numpy数据类型转换astype,dtype的方法

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

2018年08月19日  | 移动技术网IT编程  | 我要评论

淮南矿业集团朱集矿,企业搜,炮灰女配的无限逆袭

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的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网