当前位置:网站首页>numpy关于两个array叠加操作
numpy关于两个array叠加操作
2022-08-04 21:37:00 【惊瑟】
numpy中有很多关于两个array的操作,叠加方式以及叠加后的维度经常令人迷惑,这篇文章总价一下。
一、 叠加操作
- add
逐元素操作,若是array + 常量会广播到每个元素,若是array + array则要求两个array的shape一致。
end = '\n'+'*'*50+'\n'
a = np.array([[1,2],[3,4]])
b = np.array([[5,6], [7,8]])
print(a+1, end=end)
print(a+b)
输出:
[[2 3]
[4 5]]
**************************************************
[[ 6 8]
[10 12]]
- concatenate
在指定维度将两个array进行拼接,不会改变array的维度,要求两个array的维度相同,且在指定的拼接维度的array size也必须相等,值得注意的是,两个array的shape不一定一致,比较拗口,看下例子:
end = '\n'+'*'*50+'\n'
a = np.array([[1,2],[3,4]])
b = np.array([[5,6], [7,8]])
c = np.array([[5,6]])
d = np.array([5,6])
f = np.array([[5]])

a & c 的shape并不相同:
维度不一致:
长度不一致:
- stack & hstack
stack 在垂直方向上拼接两个array(可以指定axis),要求两个array的shape严格一致,结果会增加维度;
hstack 在水平方向(第0维,不可制定axis)拼接两个array,要求两者的维度相同,且在第0维的size也相同,拼接结果不改变原有维度 。
stack:结果会在原有维度的基础上加1
hstack,a和c在0轴的size不同:
hstack,转置后正常拼接:

二、 size & ndim & shape
这三个概念很容易搞混,其中:size:指的是“元素个数”;ndim:维度,指的是“有多少层嵌套”,即中括号个数,同时和shape的len相等,axis=0指的是最外层中括号,往里依次递增;shape:size和ndim综合起来就是shape,两个array的shape相同则意味着两者的ndim相同且在每一个axis上的size也相同。
看下例子:
值得注意的是,ndim和size以及shape没有必然联系,一个ndim不为0的array可能一个元素也没有:
size相同,shape和ndim也不一定相同:
边栏推荐
猜你喜欢

mysql基础

SPSS-System Clustering Hand Calculation Practice

大势所趋之下的nft拍卖,未来艺术品的新赋能

Yolov7:Trainable bag-of-freebies sets new state-of-the-art for real-time objectdetectors

数电快速入门(二)(复合逻辑运算和逻辑代数的基本定律的介绍)
![OD-Model [6]: YOLOv2](/img/3d/c81846ad0f20e055adf0192fbb8e07.png)
OD-Model [6]: YOLOv2

如何为Web3.0世界启动完美的DAO

Altium Designer 19.1.18 - 保护锁定的对象

Red team kill-free development practice of simulated confrontation

【QT】回调函数的实现
随机推荐
Some problems with passing parameters of meta and params in routing (can be passed but not passed, empty, collocation, click to pass multiple parameters to report an error)
Hands-on Deep Learning_NiN
How to solve the problem that the alarm information cannot be transmitted after EasyGBS is connected to the latest version of Hikvision camera?
硬件开发定制全流程解析
[Linear Algebra 03] Elimination method display and 4 solutions of AX=b
LayaBox---TypeScript---首次接触遇到的问题
如何将二叉搜索树转化为一个有序的双向链表(原树上修改)
C语言知识大全(一)——C语言概述,数据类型
LayaBox---TypeScript---structure
AtCoder Beginner Contest 262 D - I Hate Non-integer Number
【PCBA program design】Grip dynamometer program
国内的PMP证书含金量到底如何
强网杯2022——WEB
dotnet enables JIT multi-core compilation to improve startup performance
OD-Model【6】:YOLOv2
数字重塑客观世界,全空间GIS发展正当其时
Altium Designer 19.1.18 - 保护锁定的对象
Red team kill-free development practice of simulated confrontation
EasyGBS接入最新版海康摄像头后无法传递告警信息该如何解决?
LayaBox---TypeScript---结构