备注:output代码的--------------
是我自己加的,在input中没有相关代码。
- 相关概念
- Numpy用于矩阵运算,ndarray表示,[1,2,3]表示1*3的一维矩阵,[[1,2],[1,2],[1,2]]表示3*2的二维矩阵。
- 数据和代码放在一个文件夹下,方便写代码。
- numpy下的数据结构需要都一致
- 取数的时候[1,3],表示取数的范围是[1,3)。0表示数据的第一行/列。
- 常用代码
- 读数
- 读取txt:
numpy.genfromtxt("_.txt",delimiter=",",dtype)
- 读取txt:
- 矩阵的行列数:
矩阵.shape
: - 函数的详细说明:
help(函数)
- 代码介绍简练,读者对于不懂的可以使用
help
- 代码介绍简练,读者对于不懂的可以使用
- 读数
- 矩阵基础知识
#input
#读数
import numpy
world_alcohol = numpy.genfromtxt("world_alcohol.txt",delimiter=',',dtype=str)
world_alcohol
world_alcohol.shape #了解矩阵行列数:995行,5列
help(help) #了解help函数用法
zhaoyue= numpy.array([[11,12,13,14],
[21,22,23,24],
[31,32,33,34],
[41,42,43,44]])
zhaoyue[1:4,1:4] #提取zhaoyue的第2,3,4行与第2,3,4列的交际的数据。
#output
array([[22, 23, 24],
[32, 33, 34],
[42, 43, 44]])
#input
#The matrix product can be performed using the dot function or method
A = np.array( [[1,1],
[0,1]] )
B = np.array( [[2,0],
[3,4]] )
print(A*B)
print ( A.dot(B))
print (np.dot(A, B))
#output
#注意这里的矩阵运算,*表示对应位置相乘,.dot表示矩阵乘法。
[[2 0]
[0 4]]
[[5 4]
[3 4]]
[[5 4]
[3 4]]
- 矩阵变形
#input
a = np.floor(10*np.random.random((3,4)))
print (a)
#output
[[2. 3. 0. 8.]
[2. 4. 3. 2.]
[7. 0. 3. 3.]]
#input
a = np.floor(10*np.random.random((3,4)))
print (a)
#output
[[2. 3. 0. 8.]
[2. 4. 3. 2.]
[7. 0. 3. 3.]]
#input
a = np.floor(10*np.random.random((2,2)))
b = np.floor(10*np.random.random((2,2)))
print(a)
print(b)
print(a.T) #矩阵转置
print(np.hstack((a,b))) #左右拼接
print(np.vstack((a,b))) #上下拼接
#output
[[1. 3.]
[1. 7.]]
--------------
[[2. 4.]
[1. 1.]]
--------------
[[1. 1.]
[3. 7.]]
--------------
[[1. 3. 2. 4.]
[1. 7. 1. 1.]]
--------------
[[1. 3.]
[1. 7.]
[2. 4.]
[1. 1.]]
- 复制
a = 5
b = a
a
与b
的id一致。
网友评论