1:Ndarray对象
NumPy 最重要的一个特点是其 N 维数组对象 ndarray,它是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引。
ndarray 对象是用于存放同类型元素的多维数组。
ndarray 中的每个元素在内存中都有相同存储大小的区域。
2:矩阵的属性:
import numpy as np
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape) #矩阵形状--(3,5)float
print(a.ndim) #ndim返回的是数组的维度,返回的只有一个数,该数即表示数组的维度。--2
print(a.dtype) #返回的数据类型 --int32
print(a.size) #返回的数据数量 --15
3:创建矩阵
import numpy as np
matrix1=np.zeros ((3,4)) #全0矩阵
matrix2=np.arange( 10, 30, 5 ) #array([10, 15, 20, 25])
matrix3=np.random.random((2,3)) #返回随机矩阵
print(matrix1)
print(matrix2)
print(matrix3)
结果
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
[10 15 20 25]
[[0.66077157 0.60367463 0.95413385]
[0.38271342 0.23516732 0.69091367]]
数据均分:
import numpy as np
from numpy import pi
matrix=np.linspace( 0, 2*pi, 100 ) #返回0到6.28均分的100各数据
print(matrix)
#重组矩阵
import numpy as np
a = np.arange(15).reshape(3, 5)
print(a)
结果:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
import numpy as np
x = np.empty([3,2], dtype = int)
y = np.ones([2,2], dtype = int)
a = np.eye(5)
print(x)
print(y)
print(a)
结果:
[[0 0]
[0 0]
[0 0]]
[[1 1]
[1 1]]
4:矩阵的操作:
#向量和矩阵都支持切片操作:
matrix = np.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
print(matrix[1:3,0:2])
结果:
[[20 25]
[35 40]]
#axis=0,表示沿着第 0 轴进行操作,即对每一列进行操作;axis=1,表示沿着第1轴进行操作,即对每一行进行操作。
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
matrix.sum(axis=0)
结果
[60 75 90]
b = a.T 矩阵转置
print (np.delete(a,1,axis = 1)) #删除第二列
#矩阵的多种乘法
import numpy as np
A = np.array( [[1,1],
[0,1]] )
B = np.array( [[2,0],
[3,4]] )
print(3*A) #所有的数字都乘以3
print(B*A) #对应数字相乘
print (A.dot(B)) #print(np.dot(A,B)) 也可以这样,矩阵乘法
print(np.sqrt(B)) #矩阵元素开根号
print (np.vdot(A,B)) #点积,对应数字相乘相加
结果
[[3 3]
[0 3]]
[[2 0]
[0 4]]
[[5 4]
[3 4]]
[[1.41421356 0. ]
[1.73205081 2. ]]
6
视图或浅拷贝
ndarray.view() 方会创建一个新的数组对象,该方法创建的新数组的维数更改不会更改原始数据的维数。
副本或深拷贝
ndarray.copy() 函数创建一个副本。 对副本数据进行修改,不会影响到原始数据,它们物理内存不在同一位置。
更多基础知识参考:
https://www.runoob.com/numpy/numpy-linear-algebra.html
学习链接:
https://www.cnblogs.com/qflyue/p/8244331.html