python数值计算扩展—— NumPy


一、NumPy简介
NumPy系统是Python的一种开源的数值计算扩展。这种工具可用来存储和处理大型矩阵,比Python自身的嵌套列表(nested list structure)结构要高效的多(该结构也可以用来表示矩阵(matrix))。

以下为官方英文介绍:
NumPy is the fundamental package for scientific computing with Python. It contains among other things:

(1)a powerful N-dimensional array object
(2)sophisticated (broadcasting) functions
(3)tools for integrating C/C++ and Fortran code
(4)useful linear algebra, Fourier transform, and random number capabilities

Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases.

二、python环境注意事项
目前python3使用也比较多,有的同学可能安装了两个版本,包括python2,Mac 在终端中输入python命令后,输出的信息还是Python 2.7。
如何让系统默认使用python3呢?按照以下步骤设置即可:
(1) 终端输入:open ~/.bash_profile,打开.bash_profile文件。
(2)修改.bash_profile文件内容 ,添加如下两行PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"
export PATH(3)添加别名 alias python=``"/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6"
(4)重新生效.bash_profile文件
source .bash_profile

经过以上四步,终端输入phtyon,出现以下内容即修改成功。



三、NumPy安装
配置好python环境后,在命令行输入:from numpy import*,如果提示以下错误,我们需要手动安装NumPy:



(1)pip安装
我们使用pip安装NumPy,前提是已经安装pip,mac默认是没有安装pip的。
如果用的是macOS自带的python2.7,直接终端输入:sudo easy_install pip,安装。
如果使用的Python3,终端输入:curl  https://bootstrap.pypa.io/get-pip.py  | python3。
安装完成后,查看pip的版本和路径。由于我分别安装了python2和3,所以也分别安装了pip的不同版本,如下:



注意:
1)使用pip install XXX
新安装的库会放在这个目录下面
python2.7/site-packages

2)使用pip3 install XXX
新安装的库会放在这个目录下面
python3.6/site-packages

在使用python3执行程序,那么就不能import python2.7/site-packages中的库。

(2)安装NumPy
终端输入:sudo pip3 install -U numpy
安装成功输出以下log:



四、NumPy使用
(1)基础
NumPy的主要对象是同类型的多维数组。它是一张表,所有元素(通常是数字)的类型都相同,并通过正整数元组索引。在NumPy中,维度称为轴。轴的数目为rank。

例如,3D空间中的点的坐标[1, 2, 1]是rank为1的数组,因为它具有一个轴。该轴的长度为3。在下图所示的示例中,数组的rank为2(它是2维的)。第一维度(轴)的长度为2,第二维度的长度为3。

[[ 1., 0., 0.],
[ 0., 1., 2.]]
NumPy的数组的类称为ndarray。别名为array。请注意,numpy.array与标准Python库的类array.array不同,后者仅处理一维数组并提供较少的功能。ndarray对象的更重要的属性是:

ndarray.ndim
数组的轴(维度)的个数。在Python世界中,维度的数量被称为rank。
ndarray.shape
数组的维度。这是一个整数的元组,表示每个维度中数组的大小。对于具有n行和m列的矩阵,shape将是(n,m)。因此,shape元组的长度就是rank或维度的个数ndim。
ndarray.size
数组元素的总数。这等于shape的元素的乘积。
ndarray.dtype
描述数组中元素类型的对象。可以使用标准Python类型创建或指定dtype。另外NumPy提供了自己的类型。例如numpy.int32、numpy.int16和numpy.float64。
ndarray.itemsize
数组中每个元素的字节大小。例如,元素为float64类型的数组的itemsize为8(=64/8),而complex32类型的数组的comitemsize为4(=32/8)。它等于ndarray.dtype.itemsize。
ndarray.data
该缓冲区包含数组的实际元素。通常,我们不需要使用此属性,因为我们将使用索引访问数组中的元素。

举例说明:

import numpy as np

#这里我们生成了一个一维数组a,从0开始,步长为1,长度为20
a = np.arange(15)
print('a:',a)

#打印a的类型,应该是array
print('a type:',type(a))

#通过函数"reshape",我们可以重新构造一下这个数组,例如,我们可以构造一个3*5的二维数组
a = a.reshape(3, 5)
print('a.reshape:',a)

#数组的维度
print('a.shape:',a.shape)

#数组的维度的个数
print('a.ndim:',a.ndim)

#数组元素总数
print('a.size:',a.size)

#数组元素类型
print('a.dtype:',a.dtype)

#数组元素的字节大小
print('a.itemsize:',a.itemsize)

对应输出如下:

a: [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
a type: <class 'numpy.ndarray'>
a.reshape: [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
a.shape: (3, 5)
a.ndim: 2
a.size: 15
a.dtype: int64
a.itemsize: 8

(2)数组创建
有几种方法来创建数组,可以使用array函数从常规Python列表或元组中创建数组。得到的数组的类型从序列中元素的类型推导出。

>>> a = array( [2,3,4] )
>>> a
array([2, 3, 4])
>>> a.dtype
dtype('int32')
>>> b = array([1.2, 3.5, 5.1])
>>> b.dtype
dtype('float64')  一个常见的错误包括用多个数值参数调用`array`而不是提供一个由数值组成的列表作为一个参数。

>>> a = array(1,2,3,4)    # WRONG

>>> a = array([1,2,3,4])  # RIGHT

(3)数组打印
当你打印一个数组,NumPy以类似嵌套列表的形式显示它,但是呈以下布局:

最后的轴从左到右打印
次后的轴从顶向下打印
剩下的轴从顶向下打印,每个切片通过一个空行与下一个隔开
一维数组被打印成行,二维数组成矩阵,三维数组成矩阵列表。

>>> a = arange(6)                         # 1d array
>>> print a
[0 1 2 3 4 5]
>>>
>>> b = arange(12).reshape(4,3)           # 2d array
>>> print b
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
>>>
>>> c = arange(24).reshape(2,3,4)         # 3d array
>>> print c
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

(4)数组运算
数组上的算术运算符使用元素级别。将创建一个新数组并用结果填充。

>>> a = np.array( [20,30,40,50] )
>>> b = np.arange( 4 )
>>> b
array([0, 1, 2, 3])
>>> c = a-b
>>> c
array([20, 29, 38, 47])
>>> b**2
array([0, 1, 4, 9])
>>> 10*np.sin(a)
array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])
>>> a<35
array([ True, True, False, False], dtype=bool)

与许多矩阵语言不同,乘法运算符*的运算在NumPy数组中是元素级别的。可以使用dot函数或方法执行矩阵乘积:

>>> A = np.array( [[1,1],
...             [0,1]] )
>>> B = np.array( [[2,0],
...             [3,4]] )
>>> A*B                         # elementwise product
array([[2, 0],
       [0, 4]])
>>> A.dot(B)                    # matrix product
array([[5, 4],
       [3, 4]])
>>> np.dot(A, B)                # another matrix product
array([[5, 4],
       [3, 4]])

某些操作(如+=和*=)可以修改现有数组,而不是创建新数组。

>>> a = np.ones((2,3), dtype=int)
>>> b = np.random.random((2,3))
>>> a *= 3
>>> a
array([[3, 3, 3],
       [3, 3, 3]])
>>> b += a
>>> b
array([[ 3.417022  ,  3.72032449,  3.00011437],
       [ 3.30233257,  3.14675589,  3.09233859]])
>>> a += b                  # b is not automatically converted to integer type
Traceback (most recent call last):
  ...
TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind'

此外,NumPy还有很多强大的功能,大家如果有需要可以到官方参考文档。


猜你喜欢

转载自blog.csdn.net/wu__di/article/details/79187680