[英]NumPy row wise search 1d array in 2d array
假設我們有 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]])
我需要一個采用 x 或 y 數組並在 z 中搜索的 function:
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 數組的出現次數。
好的,假設您不關心變量在 x 或 y 中的順序,您可以使用 Counter 來查找出現次數,並使用這些來查找 x 和 y 變量的最少出現次數。 讓它有點混亂的事實是,您可以在搜索的值中有重復項,因此再次使用 Counter 使其更容易。 但是,您不能在 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.