NumPy Array

NumPy数组的优势

通常情况下,NumPy数组存储相同数据类型的元素,这意味着只要知道元素的个数,即可确定该数组的存储空间。NumPy数组可以进行向量化操作,可对整个数组直接进行操作,而要使用Python 列表达到同样的效果的话,得使用循环在对每个元素进行操作。同时,NumPy使用了优化过的C接口,这保证了其高效的运行效率。

NumPy数组下标从0开始,元素的数据类型由特定的几种构成。可使用arrange()函数创建一个数组,并使用dtype属性获得数组元素类型。

In: a = arange(5)
In: a.dtype
Out: dtype('int64')

a是整型数组,对于32位版本的Python,此处输出是int32
可使用shape属性获得数组的形状:

In: a
Out: array([0, 1, 2, 3, 4])
In: a.shape
Out: (5,)

a是包含5个元素的一维数组。shape属性的输出是tuple(元组),此处元组中只有一个数字5,指示了数组在各个维度上(此处只有一个维度)的长度。

创建一个多维数组

创建一个二维数组m:

In: m = array([arange(2), arange(2)])
In: m
Out:
array([[0, 1],
        [0, 1]])

显示其形状m.shape:

In: m.shape
Out: (2, 2)

选择NumPy数组中的元素

下面介绍如何取出数组中的特定元素,先创建一个2x2的数组:

In: a = array([[1,2],[3,4]])
In: a
Out:
array([[1, 2],
        [3, 4]])

此处使用列表([]创建的)初始化数组中的元素,记住下标从0开始,取出元素:

In: a[0,0]
Out: 1
In: a[0,1]
Out: 2
In: a[1,0]
Out: 3
In: a[1,1]
Out: 4

NumPy 数值类型

Python拥有integer,float和complex类型,然而仍不能满足科学计算的需求。实际中,我们仍然需要更多的可变精度的数据类型。NumPy拥有大量的数据类型,大多数的NumPy数值类型以数字结尾,指示该类型数值需要的比特数。详见下表:

TypeDescription
boolBoolean (True or False) stored as a bit
intiPlatform integer (normally either int32 or int64)
int8Byte (-128 to 127)
int16Integer (-32768 to 32767)
int32Integer (-2 * 31 to 2 * 31 -1)
int64Integer (-2 * 63 to 2 * 63 -1)
uint8Unsigned integer (0 to 255)
uint16Unsigned integer (0 to 65535)
uint32Unsigned integer (0 to 2 ** 32 - 1)
uint64Unsigned integer (0 to 2 ** 64 - 1)
float16Half precision float: sign bit, 5 bits exponent, and 10 bits mantissa
float32Single precision float: sign bit, 8 bits exponent, and 23 bits mantissa
float64 or floatDouble precision float: sign bit, 11 bits exponent, and 52 bits mantissa
complex64Complex number, represented by two 32-bit floats (real and imaginary components)
complex128 or complexComplex number, represented by two 64-bit floats (real and imaginary components)

许多函数带有数值类型作为参数:

In: arange(7, dtype=uint16)
Out: array([0, 1, 2, 3, 4, 5, 6], dtype=uint16)

有些数值类型不可更改:

In: float(42.0 + 1.j)
Traceback (most recent call last):
    File "numericaltypes.py", line 45, in <module>
        print float(42.0 + 1.j)
TypeError: can't convert complex to float

上述将复数转化为实数的操作是不合法的,因为复数的虚部无法处理,但是将float转化为复数是可行的,将会把虚部置为0。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值