我有一个高度相同但宽度不同的二维 numpy 数组列表:
list_of_arrays = [np.random.rand(3,4),np.random.rand(3,5),np.random.rand(3,6)]
我想构建一个新数组,其中每一列都是我列表中数组的随机列。我可以用 for 循环来做到这一点,例如:
new_array = np.zeros((3,3))
for x in range(3):
new_array[:,x] = list_of_arrays[x][:,random.randint(0,list_of_arrays[x].shape[1])]
我觉得这不干净。我想使用类似列表理解的方法,例如
new_array = [list_of_arrays[x][:,random.randint(0,list_of_arrays[x].shape[1])] for x in range(3)]
这显然返回一个列表,而不是所需的数组。我可以将列表转换成一个数组,但这会增加一个无关的中间体。有没有简单的方法可以做到这一点?我在使用一维数组时看到的类似问题使用 numpy.fromiter,但这不适用于二维。
如果有人想提出完全不同/更清洁/更有效的方法来解决这个问题,我们也将不胜感激。
请您参考如下方法:
您可以通过遍历数组而不是索引来简化您的列表理解,
new_array = np.array([x[:,np.random.randint(0, x.shape[1])] for x in list_of_arrays]).T
In [32]: %timeit np.array([x[:,np.random.randint(0, x.shape[1])] for x in a]).T
100000 loops, best of 3: 10.2 us per loop
转置 (.T) 是因为遍历数组产生行,所以遍历 arr.T 产生列。同样,在构造数组时,每个元素都被视为一行,因此在构造之后,我们需要对其进行转置,以便将我们提供给数组构造的列表转换为列。
如果你导入标准的random模块,你可以这样做
new_array = np.array([random.choice(x.T) for x in list_of_arrays]).T
In [36]: %timeit np.array([random.choice(x.T) for x in a]).T
100000 loops, best of 3: 9.18 us per loop
速度稍快。
