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

假设我们有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],[  0,260,407,106,11]])

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

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

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

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

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

cathylia 回答:NumPy行明智搜索2d数组中的1d数组

好吧,假设您不在乎变量在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))
本文链接:https://www.f2er.com/3167094.html

大家都在问