将不同大小的nd数组附加到单个数组中

问题描述 投票:-1回答:1

我有一个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:所有输入数组必须具有相同的维数

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

python arrays numpy multidimensional-array valueerror
1个回答
0
投票

是的,这是可能的。你可以使用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

请注意,如果要在元组中传递子数组,则应将其解压缩以使尺寸匹配。

© www.soinside.com 2019 - 2024. All rights reserved.