NumPy之:数据类型

算法灵珀客
• 阅读 2658

简介

我们知道Python中有4种数字类型,分别是int,float,bool和complex。作为科学计算的NumPy,其数据类型更加的丰富。

今天给大家详细讲解一下NumPy中的数据类型。

数组中的数据类型

NumPy是用C语言来实现的,我们可以对标一下NumPy中数组中的数据类型跟C语言中的数据类型:

Numpy 中的类型C 中的类型说明
np.bool_boolBoolean (True or False) stored as a byte
np.bytesigned charPlatform-defined
np.ubyteunsigned charPlatform-defined
np.shortshortPlatform-defined
np.ushortunsigned shortPlatform-defined
np.intcintPlatform-defined
np.uintcunsigned intPlatform-defined
np.int_longPlatform-defined
np.uintunsigned longPlatform-defined
np.longlonglong longPlatform-defined
np.ulonglongunsigned long longPlatform-defined
np.half / np.float16 Half precision float: sign bit, 5 bits exponent, 10 bits mantissa
np.singlefloatPlatform-defined single precision float: typically sign bit, 8 bits exponent, 23 bits mantissa
np.doubledoublePlatform-defined double precision float: typically sign bit, 11 bits exponent, 52 bits mantissa.
np.longdoublelong doublePlatform-defined extended-precision float
np.csinglefloat complexComplex number, represented by two single-precision floats (real and imaginary components)
np.cdoubledouble complexComplex number, represented by two double-precision floats (real and imaginary components).
np.clongdoublelong double complexComplex number, represented by two extended-precision floats (real and imaginary components).

我们在Ipython环境中随机查看一下上面的类型到底是什么:

import numpy as np

In [26]: np.byte
Out[26]: numpy.int8

In [27]: np.bool_
Out[27]: numpy.bool_

In [28]: np.ubyte
Out[28]: numpy.uint8

In [29]: np.short
Out[29]: numpy.int16

In [30]: np.ushort
Out[30]: numpy.uint16

所以上面的数据类型,其底层还是固定长度的数据类型,我们看下到底有哪些:

Numpy 类型C 类型说明
np.int8int8_tByte (-128 to 127)
np.int16int16_tInteger (-32768 to 32767)
np.int32int32_tInteger (-2147483648 to 2147483647)
np.int64int64_tInteger (-9223372036854775808 to 9223372036854775807)
np.uint8uint8_tUnsigned integer (0 to 255)
np.uint16uint16_tUnsigned integer (0 to 65535)
np.uint32uint32_tUnsigned integer (0 to 4294967295)
np.uint64uint64_tUnsigned integer (0 to 18446744073709551615)
np.intpintptr_tInteger used for indexing, typically the same as ssize_t
np.uintpuintptr_tInteger large enough to hold a pointer
np.float32float
np.float64 / np.float_doubleNote that this matches the precision of the builtin python float.
np.complex64float complexComplex number, represented by two 32-bit floats (real and imaginary components)
np.complex128 / np.complex_double complexNote that this matches the precision of the builtin python complex.

所有这些类型都是 dtype 对象的实例。常用的有5种基本类型,分别是bool,int,uint,float和complex。

类型后面带的数字表示的是该类型所占的字节数。

上面表格中有一些 Platform-defined的数据类型,这些类型是跟平台相关的,在使用的时候要特别注意。

这些dtype类型可以在创建数组的时候手动指定:

>>> import numpy as np
>>> x = np.float32(1.0)
>>> x
1.0
>>> y = np.int_([1,2,4])
>>> y
array([1, 2, 4])
>>> z = np.arange(3, dtype=np.uint8)
>>> z
array([0, 1, 2], dtype=uint8)

由于历史原因,为了向下兼容,我们也可以在创建数组的时候指定字符格式的dtype。


>>> np.array([1, 2, 3], dtype='f')
array([ 1.,  2.,  3.], dtype=float32)

上面的 f 表示的是float类型。

类型转换

如果想要转换一个现有的数组类型,可以使用数组自带的astype方法,也可以调用np的强制转换方法:

In [33]: z = np.arange(3, dtype=np.uint8)

In [34]: z
Out[34]: array([0, 1, 2], dtype=uint8)

In [35]: z.astype(float)
Out[35]: array([0., 1., 2.])

In [36]: np.int8(z)
Out[36]: array([0, 1, 2], dtype=int8)
注意,上面我们使用了 float , Python将会把float 自动替换成为 np.float_,同样的简化格式还有 int == np.int_, bool == np.bool_, complex == np.complex_. 其他的数据类型不能使用简化版本。

查看类型

查看一个数组的数据类型可以使用自带的dtype属性:

In [37]: z.dtype
Out[37]: dtype('uint8')

dtype作为一个对象,本身也可以进行一些类型判断操作:

>>> d = np.dtype(int)
>>> d
dtype('int32')

>>> np.issubdtype(d, np.integer)
True

>>> np.issubdtype(d, np.floating)
False

数据溢出

一般来说,如果超出了数据的范围是会报异常的。比如我们有一个非常长的int值:

In [38]: a= 1000000000000000000000000000000000000000000000000000000000000000000000000000000

In [39]: a
Out[39]: 1000000000000000000000000000000000000000000000000000000000000000000000000000000

In [40]: np.int(1000000000000000000000000000000000000000000000000000000)
Out[40]: 1000000000000000000000000000000000000000000000000000000

In [41]: np.int32(1000000000000000000000000000000000000000000000000000000)
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-41-71feb4433730> in <module>()
----> 1 np.int32(1000000000000000000000000000000000000000000000000000000)

上面的数字太长了,超出了int32的范围,就会抛出异常。

但是NumPy的有些操作,如果超出范围之后,并不会报异常,而是正常范围,这时候我们就需要注意了:

In [43]: np.power(100, 8, dtype=np.int32)
Out[43]: 1874919424

In [44]: np.power(100, 8, dtype=np.int64)
Out[44]: 10000000000000000

NumPy提供了两个方法来测量int和float的范围,numpy.iinfo 和 numpy.finfo :

In [45]:  np.iinfo(int)
Out[45]: iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64)

In [46]: np.iinfo(np.int32)
Out[46]: iinfo(min=-2147483648, max=2147483647, dtype=int32)

In [47]: np.iinfo(np.int64)
Out[47]: iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64)

如果64位的int还是太小的话,可以使用np.float64,float64可以使用科学计数法,所以能够得到更大范围的结果,但是其精度可能会缩小。

In [48]: np.power(100, 100, dtype=np.int64)
Out[48]: 0

In [49]: np.power(100, 100, dtype=np.float64)
Out[49]: 1e+200

本文已收录于 http://www.flydean.com/02-python-numpy-datatype/

最通俗的解读,最深刻的干货,最简洁的教程,众多你不知道的小技巧等你来发现!

欢迎关注我的公众号:「程序那些事」,懂技术,更懂你!

点赞
收藏
评论区
推荐文章
Wesley13 Wesley13
3年前
java 大数基本操作
导言:  计算机中数字的表示范围是有一定的限制的,像Java中,常用的数据类型,如int、double等数据类型表示的范围都是有限的,当我们要计算的数字,其位数达到成百上千时,这些数据类型无法满足我们的需求,C语言中我们可以使用数组来储存位数,再对两个数组进行相应的运算;Java中为了处理大整数的运算,提供了一种数据类型:BigInteger,BigDe
Python进阶者 Python进阶者
3年前
Python矩阵和Numpy数组的那些事儿
大家好,我是IT共享者,人称皮皮。今天给大家介绍矩阵和NumPy数组。一、什么是矩阵?使用嵌套列表和NumPy包的Python矩阵。矩阵是一种二维数据结构,其中数字按行和列排列。二、Python矩阵1\.列表视为矩阵Python没有矩阵的内置类型。但是,可以将列表的列表视为矩阵。例:A2\.如何使用嵌套列表。A三、NumPy数组1\.
Wesley13 Wesley13
3年前
MongoDB的数据类型
一.MongoDB之丰富多彩的数据类型世界首先我们要先了解一下MongoDB中有什么样的数据类型:Object ID:Documents自生成的\_idString:字符串,必须是utf8Boolean:布尔值,true或者false(这里有坑哦~在我们大Python中TrueFalse首字母大写)Integer
Stella981 Stella981
3年前
Numpy入门(一):Numpy的安装和创建
在数据分析和机器学习中,大量的使用科学计算,Numpy提供了大型矩阵计算的方式,而这些是python标准库中所缺少的。Numpy也是许多优秀的第三方库的基础,依赖于Numpy的库非常多,后续会慢慢的进行介绍。Numpy的安装和许多的库一样,不管在windows平台下还是在linux平台下,安装Numpy的命令如下:pipinst
Stella981 Stella981
3年前
Python NumPy学习总结
一、NumPy简介其官网是:http://www.numpy.org/(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fwww.numpy.org%2F)NumPy是Python语言的一个扩充程序库。支持高级大量的维度数组与矩阵运算,
小万哥 小万哥
1年前
NumPy 双曲函数与集合操作详解
NumPy概览:使用numpy.sinh(),numpy.cosh(),numpy.tanh()计算双曲函数;示例包括求弧度值的双曲正弦、余弦。此外,numpy.arcsinh(),numpy.arccosh(),numpy.arctanh()用于求反函数。同时,NumPy提供集合操作如numpy.unique()构建唯一元素数组,numpy.union1d()求并集,numpy.intersect1d()求交集,numpy.setdiff1d()求差集,numpy.setxor1d()求对称差。
美凌格栋栋酱 美凌格栋栋酱
5个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
小万哥 小万哥
1年前
学会使用 NumPy:基础、随机、ufunc 和练习测试
NumPyNumPy是一个用于处理数组的Python库。它代表“NumericalPython”。基本随机ufunc通过测验测试学习检验您对NumPy的掌握程度。通过练习学习NumPy练习练习:请插入创建NumPy数组的正确方法。pythonarrnp.(
小万哥 小万哥
1年前
NumPy 数组创建方法与索引访问详解
NumPy创建数组NumPy中的核心数据结构是ndarray,它代表多维数组。NumPy提供了多种方法来创建ndarray对象,包括:使用array()函数array()函数是最常用的方法之一,它可以将Python列表、元组甚至其他数组转换为ndarray
小万哥 小万哥
1年前
NumPy 数组切片及数据类型介绍
NumPy数组切片NumPy数组切片用于从数组中提取子集。它类似于Python中的列表切片,但支持多维数组。一维数组切片要从一维数组中提取子集,可以使用方括号并指定切片。切片由起始索引、结束索引和可选步长组成,用冒号:分隔。语法:pythonarrs
小万哥 小万哥
1年前
NumPy 数组迭代与合并详解
NumPy数组迭代NumPy数组迭代是访问和处理数组元素的重要方法。它允许您逐个或成组地遍历数组元素。基本迭代我们可以使用Python的基本for循环来迭代NumPy数组。一维数组迭代:pythonimportnumpyasnparrnp.array(1