I need to find the row and column number of a specific index/item in a ndarray. I found nothing to do this simultaneously, so I tried to achieve this separately. In the shown code I only had at least an idea how to do this for the rows.
For this code the expected output should be 0
. My idea was to iterate over the number of entries with for i in range(0, len(array)):
. For i = 0
the wanted item is not found obviously. So if row != None:
is not fulfilled so the loop should start over. For i = 1
the condition should be fulfilled and the loop should stop there and give the correct row number. But the output is ValueError: 2 is not in list
. I found solution to avoid this error but not in the combination with a ndarray.
It feels like I just can't get behind the logic of the combination of the for
loop and the if
statement. I hope someone can help me with my problem and maybe enlighten me on how this works exactly.
array = [[0,1],
[2,3]]
row = None
item = 2
for i in range(0, len(array)):
row = array[i].index(item)
if row != None:
break
else:
continue
print(row)
CodePudding user response:
If you want a pure python solution:
target = 0
for row, lst in enumerate(array): # loop over rows
for col, value in enumerate(lst): # loop over values
if value == target:
print(row, col)
# uncomment below if you want to stop after the first match
# break
output: 0 0
However, I would recommend to use numpyn this is worth learning if you plan to do real ndarray operations:
array = [[0,1],
[2,3]]
# convert to numpy array
import numpy as np
a = np.array(array)
target = 0
# identify the coordinate for all matching values
row, col = np.nonzero(a==target)
output (there will be as many values as there are matches):
# row
array([0])
# col
array([0])
First value:
first_match = row[0], col[0]
output: (0, 0)
CodePudding user response:
To find the row and column of a specific number in a 2d array, loop through the array and use the index function
arr = [[0, 1], [2, 3]]
def find(ele):
for i in arr:
if ele in i:
row = arr.index(i)
col = i.index(ele)
print("Row: ", row, "Column: ", col)
find(1) # returns "Row: 0 Column: 1"