【发布时间】:2021-01-15 16:08:30
【问题描述】:
我有一个 numpy 数组和一个掩码,指定该数组中的哪些条目在保持其相对顺序的同时进行洗牌。举个例子:
In [2]: arr = np.array([5, 3, 9, 0, 4, 1])
In [4]: mask = np.array([True, False, False, False, True, True])
In [5]: arr[mask]
Out[5]: array([5, 4, 1]) # These entries shall be shuffled inside arr, while keeping their order.
In [6]: np.where(mask==True)
Out[6]: (array([0, 4, 5]),)
In [7]: shuffle_array(arr, mask) # I'm looking for an efficient realization of this function!
Out[7]: array([3, 5, 4, 9, 0, 1]) # See how the entries 5, 4 and 1 haven't changed their order.
我已经写了一些代码可以做到这一点,但它真的很慢。
import numpy as np
def shuffle_array(arr, mask):
perm = np.arange(len(arr)) # permutation array
n = mask.sum()
if n > 0:
old_true_pos = np.where(mask == True)[0] # old positions for which mask is True
old_false_pos = np.where(mask == False)[0] # old positions for which mask is False
new_true_pos = np.random.choice(perm, n, replace=False) # draw new positions
new_true_pos.sort()
new_false_pos = np.setdiff1d(perm, new_true_pos)
new_pos = np.hstack((new_true_pos, new_false_pos))
old_pos = np.hstack((old_true_pos, old_false_pos))
perm[new_pos] = perm[old_pos]
return arr[perm]
更糟糕的是,我实际上有两个形状为 (M,N) 的大矩阵 A 和 B。矩阵 A 保存任意值,而矩阵 B 的每一行都是掩码,用于根据我上面概述的过程对矩阵 A 的相应行进行洗牌。所以我想要的是shuffled_matrix = row_wise_shuffle(A, B)。
到目前为止,我发现的唯一方法是通过我的 shuffle_array() 函数和 for 循环。
你能想到任何 numpy'onic 方法来完成这项任务以避免循环吗?提前非常感谢您!
【问题讨论】:
标签: python arrays numpy numpy-slicing