gpt4 book ai didi

python - numpy:沿第三维连接两个数组

转载 作者:太空宇宙 更新时间:2023-11-04 08:32:56 25 4
gpt4 key购买 nike

我想向现有数据立方体添加另一个数据“切片”:

import numpy as np

a = np.array([[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], [[4, 4, 4, 4], [5, 5, 5, 5], [6, 6, 6, 6]]])
print(a.shape) # (2, 3, 4)

b = np.array([[7, 7, 7], [8, 8, 8]])
print(b.shape) # (2, 3)

c = np.concatenate([a, b], axis=2) # ValueError: all the input arrays must have same number of dimensions
print(c.shape) # wanted result: (2, 3, 5)

所以我基本上想通过将最后一个维度扩展到 2x3x5 来将 2x3 数组添加到 2x3x4 数组。值错误对我来说不太有意义,因为数组不能是相同的形状?我在这里做错了什么?

最佳答案

b 的末尾添加一个新轴,然后连接 -

np.concatenate((a, b[...,None]), axis=2)

因此,对于给定的样本 -

In [95]: np.concatenate((a, b[...,None]), axis=2).shape
Out[95]: (2, 3, 5)

关于python - numpy:沿第三维连接两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51439583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com