NumPy行明智搜索2d数组中的1d数组

时间:2019-11-04 11:36:19

标签: python arrays numpy

假设我们有x,y,z数组:

x = np.array([10, 11])

y = np.array([10, 10])

z = np.array([[ 10, 229, 261, 11, 243],
             [  10, 230, 296, 10,  79],
             [  10, 10, 10, 10,  10],
             [  0, 260, 407, 229,  79],
             [  10, 10, 11, 106, 11]])

我需要一个带有x或y数组并在z中搜索的函数:

myfunc(x, z) # should give following result:
([1, 2, 4], [1, 2, 1])

上面的第一个列表是在z中找到x的行的索引,第二个列表是每行出现x的次数。

myfunc(y, z) # should give following result:
([0, 4], [1, 2])

我确实搜索了类似的问题,并尝试实施这些问题。但是无法弄清楚如何计算2d中1d数组的出现次数。

1 个答案:

答案 0 :(得分:0)

好吧,假设您不在乎变量在x或y中的顺序,则可以使用Counter来查找出现的次数,并使用那些来查找x和y变量出现的最小次数。有点混乱的事实是,您可以在搜索值中包含重复项,因此可以再次使用Counter来简化操作。但是,您不能在2D阵列上使用counter,因此您需要遍历z。

from collections import Counter

def myfunct(x, z):
    occurences_result = []
    rows_result = []

    for row, i in enumerate(z):
        count = Counter(i)
        count_x = Counter(x)
        occurences = [int(count[x_value]/x_occ) for x_value, x_occ in count_x.items() if x_value in count]
        if len(occurences) == len(count_x):
            occurences_result.append(min(occurences))
            rows_result.append(row)
    return((occurences_result, rows_result))

print(myfunct(y,z))