简体   繁体   English

NumPy 在二维数组中逐行搜索一维数组

[英]NumPy row wise search 1d array in 2d array

Say we have x, y, z arrays:假设我们有 x、y、z arrays:

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]])

I need a function that takes x or y array and search for it in z:我需要一个采用 x 或 y 数组并在 z 中搜索的 function:

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

first list above is index of rows in z where x is found, second list is number of time x occurred in each row.上面的第一个列表是 z 中找到 x 的行的索引,第二个列表是每行中出现 x 的次数。

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

I did search for similar questions and tried to implement those.我确实搜索了类似的问题并尝试实施这些问题。 But couldn't figure out how to count occurrences of 1d array in 2d.但无法弄清楚如何计算 2d 中 1d 数组的出现次数。

Ok, assuming you don't care about the order of your variables inside x or y you can use Counter to find the number of occurrences and use those to find the minimum of occurrences of you x and y variables.好的,假设您不关心变量在 x 或 y 中的顺序,您可以使用 Counter 来查找出现次数,并使用这些来查找 x 和 y 变量的最少出现次数。 What makes it a bit messy is the fact, that you can have duplicates in your searched for values, so there again use Counter to make it easier.让它有点混乱的事实是,您可以在搜索的值中有重复项,因此再次使用 Counter 使其更容易。 You can't use counter on a 2D-Array however, so you need to iterate over your z.但是,您不能在 2D-Array 上使用 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM