markdown Python numpy矩阵数组操作基本语法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Python numpy矩阵数组操作基本语法相关的知识,希望对你有一定的参考价值。
# numpy 向量操作
## 求向量模长
``````
import numpy as np
x = np.array([1,2,3,4,5])
np.linalg.norm(x) # 默认求二范数
np.linalg.norm(x,ord=1) # 求一范数
``````
![](https://ws1.sinaimg.cn/large/cdd040eely1g1ivoq3tmhj20h005swep.jpg)
## 求两个向量叉乘(cross product)
``````
numpy.cross(a,b,axisa=-1, axisb=-1, axisc=-1, axis=None)
``````
``````
x = [1, 2, 3]
y = [4, 5, 6]
np.cross(x, y)
# Output:array([-3, 6, -3])
``````
# numpy矩阵操作
## 矩阵乘法
``````
# 矩阵:
A = np.array([[1, 2, 3], [4, 5, 6]]) # 2 x 3矩阵
B = np.array([[1, 2], [3, 4], [5, 6]]) # 3 x 2矩阵
np.dot(A,B)
# Output: [[22 28]
[49 64]]
# 向量:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
np.dot(a,b)
# Output: 32
``````
## 两矩阵对应元素相乘(数乘)
``````
A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([[7, 8, 9], [4, 7, 1]])
A * B
# 等价于np.multiply(A,B)
# Output:[[ 7 16 27]
[16 35 6]]
``````
## 两矩阵的拼接
``````
a = array([0, 1, 2],
[3, 4, 5],
[6, 7, 8])
b = array([ 0, 2, 4],
[ 6, 8, 10],
[12, 14, 16])
# 按垂直方向堆叠
c = np.vstack((a,b))
# Output:
c = array([ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 0, 2, 4],
[ 6, 8, 10],
[12, 14, 16])
# 按水平方向拼接
d = np.hstack((a,b))
# Output:
d = array([ 0, 1, 2, 0, 2, 4],
[ 3, 4, 5, 6, 8, 10],
[ 6, 7, 8, 12, 14, 16])
# 按深度方向堆叠
e = np.dstack((a,b))
# Output:
e = array([[ 0, 0],
[ 1, 2],
[ 2, 4],
[ 3, 6],
[ 4, 8],
[ 5, 10],
[ 6, 12],
[ 7, 14],
[ 8, 16]])
# 多维矩阵按任意axis堆叠
f = np.concatenate((a,b),axis=1) # axis = 1相当于水平堆叠
``````
## 所有矩阵元素取exp
``````
np.exp(A)
``````
# 矩阵的保存和读取
``````
filename1 = 'train_leftleg_pos.dat'
import _pickle as pickle
output1 = open(filename1, 'wb')
pickle.dump(train, output1)
file1 = open(filename1, 'rb')
train = pickle.load(file1)
file1.close()
``````
以上是关于markdown Python numpy矩阵数组操作基本语法的主要内容,如果未能解决你的问题,请参考以下文章
Python 关于数组矩阵变换函数numpy.nonzero(),numpy.multiply()用法
42-python中的矩阵多维数组----numpy
cupy或numpy中"数组"与"矩阵"的区别
python 的矩阵运算——numpy
python数据分析-02numpy库
numpy创建字符串类型矩阵