(1)numpy.sum() #相加。没有axis参数表示全部相加,axis=0表示按列相加,axis=1表示按照行的方向相加.
import numpy as np
>>> a=np.sum([[0,1,2],[2,1,3]])
>>> a
9
>>> a=np.sum([[0,1,2],[2,1,3]],axis=0)
>>> a
array([2, 2, 5])
>>> a.shape
(3,)
>>> a=np.sum([[0,1,2],[2,1,3]],axis=1)
>>> a
array([3, 6])
>>> a.shape
(2,)
(2)random.rand(3,3) #构造一个3*3的随机数组
In [23]:random.rand(3,3)
Out[23]:
array([[ 0.68078538, 0.04810055, 0.89237689],
[ 0.52380624, 0.74562381, 0.50066403],
[ 0.57931518, 0.86270485, 0.089004 ]])
(3)mat(random.rand(3,3)) #将3*3的随机数组转化为一个3*3的矩阵
In [24]:mat(random.rand(3,3))
Out[24]:
matrix([[ 0.11921999, 0.62176972, 0.57668133],
[ 0.36761748, 0.32223052, 0.60415149],
[ 0.16873549, 0.03998786, 0.33666076]])
(4)shape() #读取矩阵的长度。shape[0]就是读取矩阵第一维度的长度,shape[1]就是读取矩阵第二维度的长度。
In [26]:matDemo = mat(random.rand(3,5))
In [27]:matDemo.shape[0]
Out[27]: 3
In [28]:matDemo.shape[1]
Out[28]: 5
In [29]:shape(matDemo)
Out[29]: (3, 5)
(5)means( ) #求平均值,axis=None时计算数组中的所有值的平均值 ,axis=0时以列为单位计算数组的每列的所有值的平均值 ,axis=1时计算数组的每行为单位的所有值的平均值 ,dtype为指定数组中元素的类型,默认为float64
In [41]:a
Out[41]:
array([[1, 2],
[3, 4]])
In [42]:mean(a)
Out[42]: 2.5
In [43]:mean(a,axis = 0)
Out[43]: array([ 2., 3.])
In [44]:mean(a,axis = 1)
Out[44]: array([ 1.5, 3.5])
(6)a.T #转置
In [48]:a = array([[1, 2], [3, 4]])
In [48]:a.T
Out[49]:
array([[1, 3],
[2, 4]])
(7)reshape() #重塑数组的维数而不改变原来的数据
In [50]: b = array([1,2,3,4,5,6,7,8])
In [51]: c = b.reshape((2,4))
In [52]: c
Out[52]:
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
In [53]: d = b.reshape((2,2,2))
In [54]: d
Out[54]:
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
In [55]: e = b.reshape((3,3)) #不能改变数组原来的元素
Traceback (most recent call last):
File "<ipython-input-55-b3c555f1a0b0>", line 1, in <module>
e = b.reshape((3,3))
ValueError: cannot reshape array of size 8 into shape (3,3)
(8)dot() #矩阵点乘
In [58]: a = array([[1,2],[3,4]])
In [59]: b = array([[2,3],[4,5]])
In [60]: c = dot(a,b)
In [61]: c
Out[61]:
array([[10, 13],
[22, 29]])