我想沿着一个特定的轴交错多个不同尺寸的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)
不幸的是,如果输入形状在第一个维度上不匹配,上面的抛出一个异常,因为我们必须沿着一个不同于不匹配的轴连接。实际上,我看不到任何有效使用连接的方法,因为沿着不匹配的轴连接会破坏生成所需输出所需的信息。你知道吗
我的另一个想法是用空条目填充输入数组,直到它们的形状与第一个维度匹配,然后在一天结束时删除空条目。虽然这会奏效,但我不确定如何最好地实施它,而且似乎一开始就没有必要这样做。你知道吗
下面是一种主要基于} 将数组与填充值交错:
NumPy
的方法,使用^{你可能在找^{} 。使用正确构造的索引,您可以在一次调用中生成结果:
range(m * n)
是所有数组大小相同时输出空间的大小。divmod
计算交织元素及其所选数组。由于数组太短而丢失的元素将被跳过,因此结果仅从数组中选择有效元素。你知道吗制作索引可能有更好的方法,但这只是一个例子。您必须move将堆栈轴移动到第一个位置,因为
choose
沿第一个轴移动。你知道吗我继续归纳了yatu对我在实践中面临的情况的回答,在这种情况下,维度的数量是任意的。以下是我所拥有的:
测试:
欢迎任何建议!特别是,在我的应用程序中,空间而不是时间是限制因素,所以我想知道是否有一种方法可以使用更少的内存(数据集沿着合并轴很大)。你知道吗
相关问题 更多 >
编程相关推荐