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数值类型以数字结尾,指示该类型数值需要的比特数。详见下表:
Type | Description |
---|---|
bool | Boolean (True or False) stored as a bit |
inti | Platform integer (normally either int32 or int64) |
int8 | Byte (-128 to 127) |
int16 | Integer (-32768 to 32767) |
int32 | Integer (-2 * 31 to 2 * 31 -1) |
int64 | Integer (-2 * 63 to 2 * 63 -1) |
uint8 | Unsigned integer (0 to 255) |
uint16 | Unsigned integer (0 to 65535) |
uint32 | Unsigned integer (0 to 2 ** 32 - 1) |
uint64 | Unsigned integer (0 to 2 ** 64 - 1) |
float16 | Half precision float: sign bit, 5 bits exponent, and 10 bits mantissa |
float32 | Single precision float: sign bit, 8 bits exponent, and 23 bits mantissa |
float64 or float | Double precision float: sign bit, 11 bits exponent, and 52 bits mantissa |
complex64 | Complex number, represented by two 32-bit floats (real and imaginary components) |
complex128 or complex | Complex 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。