失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Numpy数据类型转换astype dtype

Numpy数据类型转换astype dtype

时间:2019-11-30 17:50:28

相关推荐

Numpy数据类型转换astype dtype

1、查看数据类型

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

2、转换数据类型

// 如果将浮点数转换为整数,则小数部分会被截断In [7]: arr2 = np.array([1.1, 2.2, 3.3, 4.4, 5.3221])In [8]: arr2Out[8]: array([ 1.1 , 2.2 , 3.3 , 4.4 , 5.3221])// 查看当前数据类型In [9]: arr2.dtypeOut[9]: dtype('float64')// 转换数据类型 float -> intIn [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_stringsOut[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》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。