查找数组中某些元素的所有组合

时间:2019-03-27 11:09:53

标签: python numpy

我有一个多维numpy数组和一个对象列表,该numpy数组的某些值为None

找到所有可能的组合以用列表中的对象填充None值的最佳方法是什么?

例如,如果我的数组是

arr = [
    [1, None, 3],
    [9, 4, None],
]    

列表是

ls = [9, 8]

我想找到这些

arr = [
    [1, 9, 3],
    [9, 4, 8],
]  
arr = [
    [1, 8, 3],
    [9, 4, 9],
]

2 个答案:

答案 0 :(得分:3)

一种方法是使用掩码以ls中的值填充数组的无效条目,其次数是ls排列的次数。

但是,可以通过将这些排列的长度设置为arr中无效条目的数量来使其更加健壮。这样,我们也可以解决len(ls) > (x == None).sum()的情况。

可以使用itertools.permutations获得排列:

def fill_combs(x, fill, replace=None):
    from itertools import permutations
    m = x == replace
    for i in permutations(fill, int(m.sum())):
        x_ = x.copy()
        x_[m] = np.array(i)
        yield x_.astype(int)

样品运行:

arr = np.array([
    [1, None, 3],
    [9, 4, None],
])
ls = [9, 8]

list(fill_with_permut(arr, ls))

输出:

[array([[1, 9, 3],
        [9, 4, 8]]), 
 array([[1, 8, 3],
        [9, 4, 9]])]

或者对于更大的ls

ls = [3,5,2]
list(fill_with_permut(arr, ls))

[array([[1, 3, 3],
        [9, 4, 5]]), 
 array([[1, 3, 3],
        [9, 4, 2]]), 
 array([[1, 5, 3],
        [9, 4, 3]]), 
 array([[1, 5, 3],
        [9, 4, 2]]), 
 array([[1, 2, 3],
        [9, 4, 3]]),
 array([[1, 2, 3],
        [9, 4, 5]])]

答案 1 :(得分:1)

def update(arr, items):
    count = 0
    for i, x in enumerate(arr):
        if None in x:
            arr[i][x.index(None)] = items[count]
            count += 1
    return arr

import itertools
ls = [9, 8]
ls_ = list(itertools.permutations(ls))

for items in ls_:
    arr = [[1, None, 3],
           [9, 4, None]]
    print (update(arr,items))

输出:

[[1, 9, 3], [9, 4, 8]]
[[1, 8, 3], [9, 4, 9]]

示例:ls = [9, 8, 15]

输出:

[[1, 9, 3], [9, 4, 8]]
[[1, 9, 3], [9, 4, 15]]
[[1, 8, 3], [9, 4, 9]]
[[1, 8, 3], [9, 4, 15]]
[[1, 15, 3], [9, 4, 9]]
[[1, 15, 3], [9, 4, 8]]