[Python]Numpy入门教程

在imooc网上对numpy的入门教程(http://www.imooc.com/video/15035)进行了学习,故此记录。

一.什么是Numpy

引自百度百科:Numpy(Numeric Python)系统是Python的一种开源的数值计算扩展。这种工具可用来存储和处理大型矩阵,比Python自身的嵌套列表结构要高效的多。Numpy提供了许多高级的数值编程工具,如:矩阵数据类型,矢量处理,以及精密的运算库。

在Python中引入Numpy:

>>> import numpy as np
>>> print np.version.version
1.13.1


二.多维数组

1.(1)使用numpy.array方法生成二维数组:

>>> lst = [[1,2,3],[4,5,6]]
>>> nlst = np.array(lst, dtype=np.float16)


(2)numpy.array方法的参数可以为list或者tuple:

tuple:

>>> nlst = np.array(((1,2,3),(4,5,6)))

list:

>>> nlst = np.array([[1,2,3],[4,5,6]])

注意:list或者tuple都可以是任意维的


(3)使用dtype方法指定数组中每个元素的类型:

dtype包括bool, string, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float8, float16, float32, float64, complex(复数)等...

注意:如果没有指定dtype,numpy.array()方法中的list或者tuple的类型可以为任意的,同一个list或者tuple中的数据类型也可以不同。

如果指定了dtype,numpy.array()方法中的list或者tuple的类型应当与dtype相符。

>>> nlst = np.array([[1,2,3],[4,'c',6]])
>>> nlst = np.array([[1,2,3],[4,'c',6]], dtype=np.float64)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: c

第一种方式可以,第二种方式会报错。


(4)查看数组属性
使用type方法查看数组类型:
>>> nlst = np.array([[1,2,3],[4,5,6]])
>>> print type(nlst)
<type 'numpy.ndarray'>

使用dim查看数组维度:
>>> print nlst.ndim
2

使用shape查看数组每个维度的大小:
>>> print nlst.shape
(2, 3)

使用dtype查看数组中元素的类型:
>>> print nlst.dtype
int64

使用itemsize查看数组中元素的数据类型大小:
int64占据8个bytes
>>> print nlst.itemsize
8

使用size查看数组中元素的个数:
>>> print nlst.size
6

2.使用numpy.arange()方法生成等差数列

numpy.arange(x,y,z)

其中,x,y指定了等差数列的范围[x,y)(左闭右开),z指定了数组元素之间的差。x默认为0, z默认为1。np.arange方法至少要指定一个参数y。

>>> nlst = np.arange(11)
>>> print nlst
[ 0  1  2  3  4  5  6  7  8  9 10]
>>> print np.arange(2,12,3)
[ 2  5  8 11]
>>> print np.arange(2,12,5)
[2 7]
>>> print np.arange()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Required argument 'start' (pos 1) not found


3.使用numpy.linspace()方法生成等差数列

numpy.linspace(x,y,z)

其中,x,y指定了等差数列的范围[x,y](左闭右闭),z指定了数组元素的个数,z默认为50个。np.linspace方法至少要指定两个参数x和y。

>>> print np.linspace(1,3,10)
[ 1.          1.22222222  1.44444444  1.66666667  1.88888889  2.11111111
  2.33333333  2.55555556  2.77777778  3.        ]
>>> print np.linspace(1,3,5)
[ 1.   1.5  2.   2.5  3. ]
>>> print np.linspace(1,3,3)
[ 1.  2.  3.]
>>> print np.linspace(1,3)
[ 1.          1.04081633  1.08163265  1.12244898  1.16326531  1.20408163
  1.24489796  1.28571429  1.32653061  1.36734694  1.40816327  1.44897959
  1.48979592  1.53061224  1.57142857  1.6122449   1.65306122  1.69387755
  1.73469388  1.7755102   1.81632653  1.85714286  1.89795918  1.93877551
  1.97959184  2.02040816  2.06122449  2.10204082  2.14285714  2.18367347
  2.2244898   2.26530612  2.30612245  2.34693878  2.3877551   2.42857143
  2.46938776  2.51020408  2.55102041  2.59183673  2.63265306  2.67346939
  2.71428571  2.75510204  2.79591837  2.83673469  2.87755102  2.91836735
  2.95918367  3.        ]
>>> print np.linspace(1,2)
[ 1.          1.02040816  1.04081633  1.06122449  1.08163265  1.10204082
  1.12244898  1.14285714  1.16326531  1.18367347  1.20408163  1.2244898
  1.24489796  1.26530612  1.28571429  1.30612245  1.32653061  1.34693878
  1.36734694  1.3877551   1.40816327  1.42857143  1.44897959  1.46938776
  1.48979592  1.51020408  1.53061224  1.55102041  1.57142857  1.59183673
  1.6122449   1.63265306  1.65306122  1.67346939  1.69387755  1.71428571
  1.73469388  1.75510204  1.7755102   1.79591837  1.81632653  1.83673469
  1.85714286  1.87755102  1.89795918  1.91836735  1.93877551  1.95918367
  1.97959184  2.        ]
>>> print np.linspace(1,1)
[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.
  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.
  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
>>> print np.linspace(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: linspace() takes at least 2 arguments (1 given)


三.矩阵

1.使用numpy.zeros方法构造全零矩阵

numpy.zeros方法的参数为矩阵的shape

>>> print np.zeros([2,4])
[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]


2.使用numpy.ones方法构造全一矩阵

numpy.ones方法的参数为矩阵的shape

>>> print np.ones([3,5])
[[ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]]


3.使用numpy.eye方法构造对角线矩阵

numpy.eye方法的参数为矩阵的大小,只有一个参数

>>> print np.eye(3)
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]


4.使用reshape方法构造任意shape的矩阵

>>> print np.arange(1,11).reshape(2,5)
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]]


四.随机数

1. 使用numpy.random.rand方法生成任意随机数

numpy.random.rand(x,y,z)

表示随机数的shape为x,y,z...,参数也可以为空,表示只生成一个随机数

>>> print np.random.rand(2)
[ 0.55750001  0.32018193]
>>> print np.random.rand(2,3)
[[ 0.67643561  0.73340354  0.15798435]
 [ 0.9095994   0.42100939  0.68524279]]
>>> print np.random.rand(2,3,4)
[[[ 0.61475145  0.69820104  0.98380555  0.94939185]
  [ 0.16583245  0.4105124   0.23284564  0.44771767]
  [ 0.58465882  0.43563935  0.0375019   0.18387919]]


 [[ 0.20017906  0.23799814  0.68309734  0.03054782]
  [ 0.07199248  0.83509683  0.56054471  0.41717739]
  [ 0.28308406  0.90862957  0.60933728  0.85992027]]]
>>> print np.random.rand()
0.0501281429998


2.使用np.random.randint方法生成随机整数

np.random.randint(x,y,z),参数x和参数y指定了随机数的范围[x,y)(左闭右开),z指定了生成的随机数的个数。其中,x默认为0,z默认为1.

np.random.randint方法最少需要指定一个参数y。

>>> print np.random.randint(2)
1
>>> print np.random.randint(2)
0
>>> print np.random.randint(1,5,4)
[1 1 3 3]
>>> print np.random.randint(-1,10,12)
[ 1  9  5  7 -1 -1 -1  9  3  9  7  6]
>>> print np.random.randint()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mtrand.pyx", line 905, in mtrand.RandomState.randint (numpy/random/mtrand/mtrand.c:15752)
TypeError: randint() takes at least 1 positional argument (0 given)


3. 使用numpy.random.randn方法生成正态分布的随机数

numpy.random.randn(x,y,z)

表示随机数的shape为x,y,z...,参数也可以为空,表示只生成一个随机数

>>> print np.random.randn()
-1.26442307795
>>> print np.random.randn(2,3)
[[ 0.82840827  0.45921508  2.59825829]
 [-1.52275284  1.16471939 -0.08227251]]
>>> print np.random.randn(2,3,4)
[[[-0.2473765   1.52189224 -0.01250112 -1.54577017]
  [-0.95470518 -0.9781429   1.28363354 -0.28314614]
  [ 0.11750765  0.10897544 -0.50437335  0.51158487]]


 [[-1.92920176  1.04272466 -0.43805761 -0.22171928]
  [-0.60888476 -0.52337761 -0.36497187 -0.2276665 ]
  [-0.15758244 -0.77795301  0.12480624 -0.82467094]]]


4.使用np.random.choice方法在指定范围中选择数

np.random.choice(x),当x为list或者tuple时,指定了选择数的范围为该list或者tuple中包含的数; 当x为>0的整数时,指定了选择数的范围为[0,x)

np.random.choice(x,y),y指定随机数的shape

>>> print np.random.choice(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mtrand.pyx", line 1115, in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:17104)
ValueError: a must be greater than 0
>>> print np.random.choice(1.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mtrand.pyx", line 1113, in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:17060)
ValueError: a must be 1-dimensional or an integer
>>> print np.random.choice(2)
1
>>> print np.random.choice((2,3))
3
>>> print np.random.choice([2,3])
2
>>> print np.random.choice(2,3)
[0 1 1]
>>> print np.random.choice(2,4)
[1 0 1 1]
>>> print np.random.choice(2,3,4)
[0 1 0]
>>> print np.random.choice(2,[3,4])
[[1 1 0 1]
 [1 0 1 0]
 [1 1 0 1]]
>>> print np.random.choice((2,3,5),(2,3))
[[2 5 3]
 [5 5 5]]


5.使用numpy.random.uniform方法在均匀分布中随机采样

np.random.uniform(x,y,z),参数x和参数y指定了随机数的范围[x,y)(左闭右开),z指定了生成的随机数的个数。其中,x默认为0,y默认为1, z默认为1.

np.random.uniform方法可以不需要参数。

>>> print np.random.uniform(-1,1)
0.0465860330429
>>> print np.random.uniform(-1,1,6)
[-0.42031748  0.54952773  0.06990097  0.48707281  0.21660118  0.51027754]
>>> print np.random.uniform(-1)
0.380192889576
>>> print np.random.uniform()
0.580514461971


五.元素操作

生成2行5列的矩阵

>>> lst = np.arange(10).reshape(2,5)
>>> print lst
[[0 1 2 3 4]
 [5 6 7 8 9]]

1.使用numpy.exp方法求exp(矩阵元素)

>>> print np.exp(lst)
[[  1.00000000e+00   2.71828183e+00   7.38905610e+00   2.00855369e+01
    5.45981500e+01]
 [  1.48413159e+02   4.03428793e+02   1.09663316e+03   2.98095799e+03
    8.10308393e+03]]


2.使用numpy.exp2方法求pow(2,矩阵元素)

>>> print np.exp2(lst)
[[   1.    2.    4.    8.   16.]
 [  32.   64.  128.  256.  512.]]


3.使用numpy.sqrt方法求每个矩阵元素的开平方

>>> print np.sqrt(lst)
[[ 0.          1.          1.41421356  1.73205081  2.        ]
 [ 2.23606798  2.44948974  2.64575131  2.82842712  3.        ]]


4.使用numpy.sin方法求每个矩阵元素的三角函数

>>> print np.sin(lst)
[[ 0.          0.84147098  0.90929743  0.14112001 -0.7568025 ]
 [-0.95892427 -0.2794155   0.6569866   0.98935825  0.41211849]]


5.使用numpy.log方法求每个矩阵元素的对数

>>> print np.log(lst)
__main__:1: RuntimeWarning: divide by zero encountered in log
[[       -inf  0.          0.69314718  1.09861229  1.38629436]
 [ 1.60943791  1.79175947  1.94591015  2.07944154  2.19722458]]


6.使用sum方法计算元素的和

>>> print lst.sum()
45

可以在sum方法中指定axis来计算不同维度的sum值。

>>> print lst.sum(axis=0)
[ 5  7  9 11 13]
>>> print lst.sum(axis=1)
[10 35]


7.使用max和min方法来获得元素的最大值或者最小值

>>> print lst.max()
9
>>> print lst.min()
0
>>> print lst.max(axis=0)
[5 6 7 8 9]
>>> print lst.max(axis=1)
[4 9]
>>> print lst.min(axis=0)
[0 1 2 3 4]

>>> print lst.min(axis=1)

[0 5]


六.整体间操作

>>> lst1 = np.array([1,2,3,4])
>>> lst2 = np.array([5,6,7,8])
>>> print lst1
[1 2 3 4]
>>> print lst2
[5 6 7 8]

1.相加

>>> print lst1 + lst2
[ 6  8 10 12]

2.相减

>>> print lst1 - lst2
[-4 -4 -4 -4]

3.相乘

>>> print lst1 * lst2
[ 5 12 21 32]

4.相除

>>> print lst1 / lst2
[0 0 0 0]

5.平方

>>> print lst1 ** 2
[ 1  4  9 16]


6.矩阵乘法

>>> print np.dot(lst1.reshape(2,2), lst2.reshape(2,2))
[[19 22]
 [43 50]]


7.一个数组追加到另一个数组上

>>> print np.concatenate((lst1,lst2))
[1 2 3 4 5 6 7 8]
>>> print np.concatenate((lst1,lst2), axis=0)
[1 2 3 4 5 6 7 8]

如果是矩阵,可以利用axis实现不同维度上的追加,默认axis=0。

>>> lst3 = np.arange(1,5).reshape(2,2)
>>> lst4 = np.arange(1,5).reshape(2,2)
>>> print lst3,lst4
[[1 2]
 [3 4]] 

[[1 2]
 [3 4]]
>>> print np.concatenate((lst3,lst4), axis=0)
[[1 2]
 [3 4]
 [1 2]
 [3 4]]
>>> print np.concatenate((lst3,lst4), axis=1)
[[1 2 1 2]
 [3 4 3 4]]
>>> print np.concatenate((lst3,lst4))
[[1 2]
 [3 4]
 [1 2]
 [3 4]]

或者直接使用numpy.hstack方法和numpy.vstack方法,直接进行水平和垂直方向的追加。

>>> print np.hstack((lst1,lst2))
[1 2 3 4 5 6 7 8]
>>> print np.vstack((lst1,lst2))
[[1 2 3 4]
 [5 6 7 8]]


8.数组分割

如将lst1分为两个数组

>>> print np.split(lst1,2)
[array([1, 2]), array([3, 4])]


9.数组拷贝

>>> print np.copy(lst)
[[0 1 2 3 4]
 [5 6 7 8 9]]

注意,copy方法是重新生成了一个对象

>>> lstn = np.copy(lst)
>>> lstn is lst
False
>>> lstm = lst
>>> lstm is lst
True


七.线性代数操作

引入linalg包

>>> from numpy.linalg import *

>>> lst = np.array([1,2,3,4]).reshape(2,2)
>>> print lst
[[1 2]
 [3 4]]

1.逆矩阵

>>> print inv(lst)
[[-2.   1. ]
 [ 1.5 -0.5]]

2.转置矩阵

>>> print lst.transpose()
[[1 3]
 [2 4]]

3.计算行列式

>>> print det(lst)
-2.0

4.计算特征值和特征向量

第一个数组是特征值,第二个数组是特征向量

>>> print eig(lst)
(array([-0.37228132,  5.37228132]), array([[-0.82456484, -0.41597356],
       [ 0.56576746, -0.90937671]]))

5.求解lst * W = y

>>> y = np.array([5,6,7,8]).reshape(2,2)
>>> print solve(lst,y)
[[-3. -4.]
 [ 4.  5.]]


6.求解相关系数

>>> print np.corrcoef([1,0,1],[0,2,1])
[[ 1.        -0.8660254]
 [-0.8660254  1.       ]]


仅为入门numpy使用,更深理解,需移步官方文档。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值