本篇文章主要讲述numpy转换astype,dtype的方法,具体代码展示如下:
1、查看数据类型
<p style="line-height: 1.75em"><span>In [11]: <a href="https://www.gaodaima.com/tag/arr" title="查看更多关于arr的文章" target="_blank">arr</a> = 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')<br></span></p>
www#gaodaima.com来源gaodai.ma#com搞##代!^码@网搞代码
2、转换数据类型
<p style="line-height: 1.75em"><span>// 如果将浮点数转换为整数,则小数部分会被截断 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)<br></span></p>
3、字符串数组转换为数值型
<p style="line-height: 1.75em"><span>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])<br></span></p>
numpy转换的方法还是很简单,小伙伴们快快动手尝试一下吧~更多Python学习推荐:云海天Python教程网。
来源:搞代码网:原文地址:https://www.gaodaima.com