操作系统:windows7+Anaconda3+python3.6
矩阵运算
(M行, N列) * (N行, Z列) = (M行, Z列)
import numpy as np
score = np.array([[8, 3], [5, 2], [4, 7],[6,5]])
a = np.array([[0.4],[0.6]])
np.dot(score,a)
Out[62]:
array([[5. ],
[3.2],
[5.8],
[5.4]])
行拼接
- 矩阵水平拼接
import numpy as np
In[2]: a = [[1,2,8],[0,2,5]]
In[2]: a
Out[66]: [[1, 2, 8], [0, 2, 5]]
In[2]: b = [[3,2,5],[7,2,1]]
In[2]: b
Out[68]: [[3, 2, 5], [7, 2, 1]]
In[2]: result = np.hstack((a, b))
In[2]: result
Out[70]:
array([[1, 2, 8, 3, 2, 5],
[0, 2, 5, 7, 2, 1]])
In[2]: print(result)
[[1 2 8 3 2 5]
[0 2 5 7 2 1]]
列拼接
- 矩阵垂直拼接
import numpy as np
a = [[1,2,8],[0,2,5]]
b = [[3,2,5],[7,2,1]]
c = np.vstack((a,b))
c
Out[82]:
array([[1, 2, 8],
[0, 2, 5],
[3, 2, 5],
[7, 2, 1]])
数组的索引,切片
In[2]: import numpy as np
In[3]: n_array = np.array([[1,2,3,4,5],[6,7,8,9,0],[3,4,5,6,7],[7,6,5,4,3],[6,8,9,2,3]])
In[5]: n_array
Out[5]:
array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 0],
[3, 4, 5, 6, 7],
[7, 6, 5, 4, 3],
[6, 8, 9, 2, 3]])
In[4]: n_array[:,1] #选择当前二维数组第二列
Out[4]: array([2, 7, 4, 6, 8])
n_array[1,:] #选择当前二维数组第二行
Out[6]: array([6, 7, 8, 9, 0])
创建0-23, 共2个三行四列的三维数组
a = np.arange(24).reshape((2,3,4))
a
Out[13]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])a[1][0][0]
In[14]: a[1][0][0] #获取12
Out[14]: 12
In[14]: a[1,:] # 选取第一维数组里面所有
Out[15]:
array([[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]])
In[14]: a[:, 1] # 选取所有维度 第一行
Out[16]:
array([[ 4, 5, 6, 7],
[16, 17, 18, 19]])
In[14]: a[1,:,3] # 选取第一维度数组 所有行里的 第三个值
Out[18]: array([15, 19, 23])
In[14]: a[:,0:2,1] #选取所有维度的 第0行到第2行, 取元素第1个
Out[20]:
array([[ 1, 5],
[13, 17]])
生成一个两行三列的数组
Out[7]: n_arry = np.empty((2,3))
Out[7]: n_arry
Out[7]:
array([[1.196e-321, 0.000e+000, 0.000e+000],
[0.000e+000, 0.000e+000, 0.000e+000]])
Out[7]: n_arry.astype(np.int) #将数组类型强制转换为int
Out[8]:
array([[0, 0, 0],
[0, 0, 0]])
Out[8]: n_arry = np.array([[1,2,3],[4,5,6]])
Out[8]: n_arry
Out[13]:
array([[1, 2, 3],
[4, 5, 6]])
Out[8]: n_arry.shape #返回数组的形状
Out[14]: (2, 3)
Out[16]: n_arry.shape[0] #返回数组有几行
Out[15]: 2
Out[16]: n_arry.shape[1] #返回数组有几列
Out[16]: 3
reshape改变数组形状(要求前后元素个数匹配)
In[2]: import numpy as np
In[3]: a = np.ones([6])
In[4]: a
Out[4]: array([1., 1., 1., 1., 1., 1.]) # 1行6列
In[5]: b = a.reshape([2,3]) # 改变成2行3列
In[6]: b
Out[6]:
array([[1., 1., 1.],
[1., 1., 1.]])
Numpy读取数据
读取csv格式的文件 以下两种方法效果相同
my_content = np.loadtxt(open("score.csv","rb"),delimiter=",")
my_content = np.genfromtxt("score.csv",delimiter=",") **sort排序**
sort排序
import numpy as np
a = np.array([2,5,6,8,1,12])
np.sort(a,axis=0) # axis=0 表示行
Out[4]: array([ 1, 2, 5, 6, 8, 12])
# ndarray转为python list
np.tolist()
# 数组去重,把重复去掉,并且按从小到大生成一个新的数组
np.unique(a)
# 删除数组
np.delete(a)