首页 > 解决方案 > 根据条件从 numpy 数组中随机选择行

问题描述

假设我有 2 个数组数组,标签是 1D,数据是 5D注意两个数组具有相同的第一维

为了简化事情,假设标签只包含 3 个数组:

labels=np.array([[0,0,0,1,1,2,0,0],[0,4,0,0,0],[0,3,0,2,1,0,0,1,7,0]])

假设我有一个数据数组(长度 = 3)的数据列表,其中每个数组都有一个 5D 形状,其中每个数组的第一个维度与标签数组的数组相同。

在这个例子中,datalist有 3 个形状数组:( 8 , 3,100,10,1), ( 5 ,3,100,10,1) 和 ( 10 ,3,100,10,1)在这里,每个数组的第一个维度与label中每个数组的长度相同。

现在我想减少每个标签数组中零的数量并保留其他值。假设我只想为每个数组保留3 个零。因此,标签中每个数组的长度以及数据中每个数组的第一个维度将是648

为了减少每个标签数组中零的数量,我想随机选择并只保留 3 个。现在,这些相同的随机选择索引将用于从data中选择相应的行。

对于此示例,new_labels数组将如下所示:

new_labels=np.array([[0,0,1,1,2,0],[4,0,0,0],[0,3,2,1,0,1,7,0]])

这是我到目前为止所尝试的:

all_ind=[] #to store indexes where value=0 for all arrays
indexes_to_keep=[] #to store the random selected indexes
new_labels=[] #to store the final results

for i in range(len(labels)):
    ind=[] #to store indexes where value=0 for one array
    for j in range(len(labels[i])):
        if (labels[i][j]==0):
            ind.append(j)
    all_ind.append(ind)

for k in range(len(labels)):   
    indexes_to_keep.append(np.random.choice(all_ind[i], 3))
    aux= np.zeros(len(labels[i]) - len(all_ind[i]) + 3)
    ....
    .... 
    Here, how can I fill **aux** with the values ?
    ....
    .... 
    new_labels.append(aux)

有什么建议么 ?

标签: pythonarraysnumpy

解决方案


使用不同长度的 numpy 数组并不是一个好主意,因此您需要迭代每个项目并对其执行一些方法。假设您只想优化该方法,掩码可能在这里工作得很好:

def specific_choice(x, n):
    '''leaving n random zeros of the list x'''
    x = np.array(x)
    mask = x != 0
    idx = np.flatnonzero(~mask)
    np.random.shuffle(idx) #dynamical change of idx value, quite fast
    idx = idx[:n]
    mask[idx] = True
    return x[mask] # or mask if you need it

列表的迭代比数组之一快,因此有效的用法是:

labels = [[0,0,0,1,1,2,0,0],[0,4,0,0,0],[0,3,0,2,1,0,0,1,7,0]]
output = [specific_choice(n, 3) for n in labels]

输出:

[array([0, 1, 1, 2, 0, 0]), array([0, 4, 0, 0]), array([0, 3, 0, 2, 1, 1, 7, 0])]

推荐阅读