【问题标题】:Appending different sized nd arrays into a single array将不同大小的 nd 数组附加到单个数组中
【发布时间】:2018-06-28 14:08:34
【问题描述】:

我有一个 5000*3072 的多维数组,我使用它分成 5 个 1000*3072 的块

numpy.array_split() 

功能。现在进行迭代,我需要组合数组的不同组合

For example, 0th iteration: 1,2,3,4 chunks to combine
             1st iteration: 0,2,3,4 chunks to combine
             2nd iteration: 0,1,3,4 chunks to combine and so on

我尝试使用np.concatenate,但它给出了错误:

ValueError:所有输入数组的维数必须相同

这种组合还有其他方式吗?

【问题讨论】:

  • 我希望你想沿着axis 0 进行连接。此外,有趣的是知道为什么要尝试这样的问题。如果我们将输入数组视为图像,您可能希望将行混杂以产生 对抗性灰度图像; )
  • 您尝试连接的数组形状是什么?究竟什么是串联表达式?

标签: python arrays numpy multidimensional-array valueerror


【解决方案1】:

是的,这是可能的。你可以用np.concatenate点赞

In [10]: arr = np.arange(20).reshape((5,4))

# split `arr` into 5 sub-arrays
In [11]: split_arrs = np.array_split(arr, 5)

# concatenate only last four sub-arrays
# for your case: 1,2,3,4 chunks to combine
In [12]: np.concatenate(split_arrs[1:], axis=0)
Out[12]: 
array([[ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])


# 0,2,3,4 chunks to combine
In [15]: np.concatenate((split_arrs[0], *split_arrs[2:]), axis=0)
Out[15]: 
array([[ 0,  1,  2,  3],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

# 0,1,3,4 chunks to combine
In [16]: np.concatenate((*split_arrs[0:2], *split_arrs[3:]), axis=0)
Out[16]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

我认为你得到了ValueError,因为你可能做过类似的事情:

In [17]: np.concatenate((split_arrs[0], split_arrs[2:]), axis=0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-938d5afdd06a> in <module>()
----> 1 np.concatenate((split_arrs[0], split_arrs[2:]), axis=0)

ValueError: all the input arrays must have same number of dimensions

请注意,如果您在元组中传递子数组,那么您应该解压缩它以便尺寸匹配。

【讨论】:

    猜你喜欢
    • 2021-10-25
    • 2020-07-07
    • 2018-07-15
    • 2019-08-04
    • 1970-01-01
    • 2020-09-21
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多