• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python中numpy数据类型转换的方法

python 搞java代码 3年前 (2022-05-21) 16次浏览 已收录 0个评论

本篇文章主要讲述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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python中numpy数据类型转换的方法
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址