Numpy数据类型转换astype,dtype

Numpy数据类型转换astype,dtypendarray数据类型astype: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.f

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分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/5164.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注