Numpy入门2—基本运算

1. 基本运算
数组的算数运算是按元素的
``````# 算数运算
>>> b
array([0, 1, 2, 3])
>>> b**2
array([0, 1, 4, 9])
# 逻辑运算
>>> a = array( [20,30,40,50] )
>>> a<35
array([True, True, False, False], dtype=bool)
``````
1. 矩阵乘法

image.png
``````>>> A = array( [[1,1],
...             [0,1]] )
>>> B = array( [[2,0],
...             [3,4]] )
>>> A*B                         # 对应的元素相乘
array([[2, 0],
[0, 4]])
>>> dot(A,B)                    # 矩阵乘法
array([[5, 4],
[3, 4]])
``````

3.产生一个随机数或者是随机数组

``````In [1]: import numpy as np

In [2]: b=np.random.random((2,3))
In [3]: b
Out[3]:
array([[ 0.10644283,  0.634037  ,  0.18570979],
[ 0.45308481,  0.90985876,  0.88518805]])

In [4]: b=np.random.random(1)
In [5]: b
Out[5]: array([ 0.71739024])
``````

4.获得数组里面的最大/最小/求和/平均值

``````>>> a = random.random((2,3))
>>> a
array([[ 0.6903007 ,  0.39168346,  0.16524769],
[ 0.48819875,  0.77188505,  0.94792155]])
>>> a.sum()          #数组求和
3.4552372100521485
>>> a.min()           #获得数组里面最小的数字
0.16524768654743593
>>> a.max()         #获得数组里面最大的数字
0.9479215542670073
>>> a.mean()        #获得数组的平均值
``````

5.数组的迭代

``````#一维的数组
In [11]: a=np.arange(5)
Out[12]: array([0, 1, 2, 3, 4])
In [13]: for i in a:
...:     print(i)
...:
0
1
2
3
4
#多维的数组
In [17]: a
Out[17]:
array([[0, 1, 2],
[3, 4, 5]])

In [18]: for i in a :
...:     print (i)
...:
[0 1 2]
[3 4 5]
``````

5.矩阵运算

``````>>> A = np.matrix('1.0 2.0; 3.0 4.0')
>>> A
[[ 1.  2.]
[ 3.  4.]]

>>> A.T  # transpose  矩阵的转置
[[ 1.  3.]
[ 2.  4.]]

>>> print A*Y  # matrix multiplication 矩阵乘法

>>> print A.I  # inverse  逆矩阵
[[-2.   1. ]
[ 1.5 -0.5]]
``````
Python入门