我整天都在想辦法解決這個問題,但沒有成功。先上代碼:
a = np.arange(15).reshape(5, 3)
b = np.arange(15).reshape(5, 3)
c = np.arange(10, 25).reshape(5, 3)
c[4, 0] = 1
c[4, 1] = 1
print(a)
print(b)
print(c)
y, x = np.where(a > 10)
coord = list(zip(y, x))
print(coord)
y, x = np.where(b[y, x] > c[y, x]) # this line produces error and know why
所以我想獲取 2d array 中大于 10 的元素的坐標a。然后我想使用這些坐標來比較二維陣列b和c. 如果來自位置的b元素大于來自c位置的元素,我想要該位置的坐標。
所以上面的代碼np.where(a > 10)給了我坐標:[(3, 2), (4, 0), (4, 1), (4, 2)]
然后我比較來自b和 的這些坐標元素c。我會在最后坐標 (4,0) 和 (4,1) 因為只有在這些位置元素 fromb大于元素 from c。
謝謝!
uj5u.com熱心網友回復:
發生錯誤是因為運算式:
b[y, x] > c[y, x] # the output is [False True True False]
回傳一維陣列。因此np.where回傳一個大小為 1 的元組(對應于輸入的維度)。
np.where(b[y, x] > c[y, x]) # the output is (array([1, 2]),)
一種可能的解決方案是:
y, x = np.where(a > 10)
coord = np.array(list(zip(y, x)))
y = np.where(b[y, x] > c[y, x])
result = coord[y]
print(result)
輸出
[[4 0]
[4 1]]
作為替代方案,如果您想保留元組輸出串列,請執行以下操作:
y, x = np.where(a > 10)
coord = list(zip(y, x))
y = np.where(b[y, x] > c[y, x])
result = [tt for i, tt in enumerate(coord) if i in y[0]]
print(result)
輸出
[(4, 0), (4, 1)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317004.html
上一篇:將n次多項式中的系數應用于公式
