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

yipeiwu_com6年前Python基础

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的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

opencv python 基于KNN的手写体识别的实例

OCR of Hand-written Data using kNN OCR of Hand-written Digits 我们的目标是构建一个可以读取手写数字的应用程序, 为此,我...

浅谈python中scipy.misc.logsumexp函数的运用场景

scipy.misc.logsumexp函数的输入参数有(a, axis=None, b=None, keepdims=False, return_sign=False),具体配置可参见...

Python+Django在windows下的开发环境配置图解

Python+Django在windows下的开发环境配置图解

1         安装配置开发环境 1.1   准备安装 下载以下软件 Eclipse for...

Python:合并两个numpy矩阵的实现

numpy是Python用来科学计算的一个非常重要的库,numpy主要用来处理一些矩阵对象,可以说numpy让Python有了Matlab的味道。   如何利用numpy来合并...

使用matlab或python将txt文件转为excel表格

使用matlab或python将txt文件转为excel表格

假设txt文件为: 一、matlab代码 data=importdata('data.txt'); xlswrite('data.xls',data); 二、python代码...