[英]How to find the index of a tuple in a 2D array in python?
我有一個形式如下的數組(包含更多元素):
coords = np.array(
[[(2, 1), 1613, 655],
[(2, 5), 906, 245],
[(5, 2), 0, 0]])
我想找到一個特定元組的索引。 例如,我可能正在尋找元組(2, 5)
的 position ,在這種情況下應該在 position 1
中。
我試過np.where
和np.argwhere
,但沒有運氣:
pos = np.argwhere(coords == (2,5))
print(pos)
>> DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
pos = np.where(coords == (2,5))
print(pos)
>> DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
如何獲取元組的索引?
您不應該比較 (2, 5) 和 coords,而是比較 (2, 5) 和 coords[:, 0]。
試試這個代碼。
np.where([np.array_equal(coords[:, 0][i], (2, 5)) for i in range(len(coords))])[0]
試試這個
import numpy as np
coords = np.array([[(2, 1), 1613, 655], [(2, 5), 906, 245], [(5, 2), 0, 0]])
tpl=(2,5)
i=0 # index of the column in which the tuple you are looking for is listed
pos=([t[i] for t in coords].index(tpl))
print(pos)
如果您打算使用包含對象的 numpy 數組,則所有比較都將使用 python 本身完成。 至此,你幾乎放棄了 numpy 的所有優勢,不妨用一個清單:
coords = coords.tolist()
index = next((i for i, n in enumerate(coords) if n[0] == (2, 5)), -1)
如果你真的想使用 numpy,我建議你適當地轉換你的數據。 我想到了兩個簡單的選擇。 您可以擴展元組並創建一個形狀為(N, 4)
的數組,也可以創建一個結構化數組,將數據的排列保留為一個單元,並具有形狀(N,)
。 前者更簡單,而后者在我看來更優雅。
如果你展平坐標:
coords = np.array([[x[0][0], x[0][1], x[1], x[2]] for x in coords])
index = np.flatnonzero(np.all(coords[:, :2] == [2, 5], axis=1))
結構化解決方案:
coordt = np.dtype([('x', np.int_), ('y', np.int_)])
dt = np.dtype([('coord', coordt), ('a', np.int_), ('b', np.int_)])
coords = np.array([((2, 1), 1613, 655), ((2, 5), 906, 245), ((5, 2), 0, 0)], dtype=dt)
index = np.flatnonzero(coords['coord'] == np.array((2, 5), dtype=coordt))
您也可以將數據的第一部分轉換為真正的 numpy 數組,然后對其進行操作:
coords = np.array(coords[:, 0].tolist())
index = np.flatnonzero((coords == [2, 5]).all(axis=1))
假設您的目標元組(例如(2,5)
)始終位於 numpy 數組coords
的第一列,即coords[:,0]
您可以簡單地執行以下操作而無需任何循環!
[*coords[:,0]].index((2,5))
如果元組不一定總是在第一列,那么您可以使用,
[*coords.flatten()].index((2,5))//3
希望有幫助。
首先,元組(2, 5)
在 position 0 中,因為它是列表[(2, 5), 906, 245]
的第一個元素。
其次,您可以使用基本的 python 函數來檢查該數組中元組的索引。 這是你如何做到的:
>>> coords = np.array([[(2, 1), 1613, 655], [(2, 5), 906, 245], [(5, 2), 0, 0]])
>>>
>>> coords_list = cl = list(coords)
>>> cl
[[(2, 1), 1613, 655], [(2, 5), 906, 245], [(5, 2), 0, 0]]
>>>
>>> tuple_to_be_checked = tuple_ = (2, 5)
>>> tuple_
(2, 5)
>>>
>>> for i in range(0, len(cl), 1): # Dynamically works for any array `cl`
for j in range(0, len(cl[i]), 1): # Dynamic; works for any list `cl[i]`
if cl[i][j] == tuple_: # Found the tuple
# Print tuple index and containing list index
print(f'Tuple at index {j} of list at index {i}')
break # Break to avoid unwanted loops
Tuple at index 0 of list at index 1
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.