简体   繁体   中英

How to find the index of a tuple in a 2D array in python?

I have an array with the form as follows (with much more elements):

coords = np.array(
    [[(2, 1), 1613, 655],
     [(2, 5), 906, 245],
     [(5, 2), 0, 0]])

And I would like to find the index of a specific tuple. For example, I might be looking for the position of the tuple (2, 5) , which should be in position 1 in this case.

I have tried with np.where and np.argwhere , with no luck:

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.

How can I get the index of a tuple?

You should not compare (2, 5) and coords, but compare (2, 5) and coords[:, 0].

Try this code.

np.where([np.array_equal(coords[:, 0][i], (2, 5)) for i in range(len(coords))])[0]

Try this one

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)

If you intend to use a numpy array containing objects, all comparison will be done using python itself. At that point, you have given up almost all the advantages of numpy and may as well use a list:

coords = coords.tolist()
index = next((i for i, n in enumerate(coords) if n[0] == (2, 5)), -1)

If you really want to use numpy, I suggest you transform your data appropriately. Two simple options come to mind. You can either expand your tuple and create an array of shape (N, 4) , or you can create a structured array that preserves the arrangement of the data as a unit, and has shape (N,) . The former is much simpler, while the later is, in my opinion, more elegant.

If you flatten the coordinates:

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))

The structured solution:

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))

You can also just transform the first part of your data to a real numpy array, and operate on that:

coords = np.array(coords[:, 0].tolist())
index = np.flatnonzero((coords == [2, 5]).all(axis=1))

Assuming your target tuple (eg (2,5) ) is always in the first column of the numpy array coords ie coords[:,0] you can simply do the following without any loops!

[*coords[:,0]].index((2,5))

If the tuples aren't necessarily in the first column always, then you can use,

[*coords.flatten()].index((2,5))//3

Hope that helps.

First of all, the tuple (2, 5) is in position 0 as it is the first element of the list [(2, 5), 906, 245] .
And second of all, you can use basic python functions to check the index of a tuple in that array. Here's how you do it:

>>> 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
>>> 

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