简体   繁体   中英

NumPy row wise search 1d array in 2d array

Say we have 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:

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.

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.

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. 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. You can't use counter on a 2D-Array however, so you need to iterate over your 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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