我想沿特定轴交错具有不同维度的多个 numpy 数组。特别是,我有一个 shape 数组列表(_, *dims)
,沿第一个轴变化,我想将其交错以获得另一个 shape 数组(_, *dims)
。例如,给定输入
a1 = np.array([[11,12], [41,42]])
a2 = np.array([[21,22], [51,52], [71,72], [91,92], [101,102]])
a3 = np.array([[31,32], [61,62], [81,82]])
interweave(a1,a2,a3)
所需的输出将是
np.array([[11,12], [21,22], [31,32], [41,42], [51,52], [61,62], [71,72], [81,82], [91,92], [101,102]]
在以前的帖子(例如Numpy concatenate arrays with interleaving)的帮助下,当数组沿第一个维度匹配时,我已经完成了这项工作:
import numpy as np
def interweave(*arrays, stack_axis=0, weave_axis=1):
final_shape = list(arrays[0].shape)
final_shape[stack_axis] = -1
# stack up arrays along the "weave axis", then reshape back to desired shape
return np.concatenate(arrays, axis=weave_axis).reshape(final_shape)
不幸的是,如果输入的形状在第一个维度上不匹配,上面会抛出异常,因为我们必须沿着与不匹配的轴不同的轴连接。事实上,我看不到任何有效地使用连接的方法,因为沿着不匹配的轴连接会破坏我们产生所需输出所需的信息。
我的另一个想法是用空条目填充输入数组,直到它们的形状沿第一个维度匹配,然后在一天结束时删除空条目。虽然这可行,但我不确定如何最好地实施它,而且似乎一开始就没有必要。