How to find the index of a value in 2d array in Python?
You can use np.where
to return a tuple of arrays of x and y indices where a given condition holds in an array.
If a
is the name of your array:
>>> np.where(a == 1)
(array([0, 0, 1, 1]), array([0, 1, 2, 3]))
If you want a list of (x, y) pairs, you could zip
the two arrays:
>>> list(zip(*np.where(a == 1)))
[(0, 0), (0, 1), (1, 2), (1, 3)]
Or, even better, @jme points out that np.asarray(x).T
can be a more efficient way to generate the pairs.
How do I find .index of a multidimensional array
a.each_index { |i| j = a[i].index 'S'; p [i, j] if j }
Update: OK, we can return multiple matches. It's probably best to utilize the core API as much as possible, rather than iterate one by one with interpreted Ruby code, so let's add some short-circuit exits and iterative evals to break the row into pieces. This time it's organized as an instance method on Array, and it returns an array of [row,col] subarrays.
a = [ %w{ a b c d },
%w{ S },
%w{ S S S x y z },
%w{ S S S S S S },
%w{ x y z S },
%w{ x y S a b },
%w{ x },
%w{ } ]
class Array
def locate2d test
r = []
each_index do |i|
row, j0 = self[i], 0
while row.include? test
if j = (row.index test)
r << [i, j0 + j]
j += 1
j0 += j
row = row.drop j
end
end
end
r
end
end
p a.locate2d 'S'
Javascript 2d array indexOf
You cannot use indexOf to do complicated arrays (unless you serialize it making everything each coordinate into strings), you will need to use a for loop (or while) to search for that coordinate in that array assuming you know the format of the array (in this case it is 2d).
var arr = [[2,3],[5,8],[1,1],[0,9],[5,7]];
var coor1 = [0, 9];
var coor2 = [1, 2];
function isItemInArray(array, item) {
for (var i = 0; i < array.length; i++) {
// This if statement depends on the format of your array
if (array[i][0] == item[0] && array[i][1] == item[1]) {
return true; // Found it
}
}
return false; // Not found
}
// Test coor1
console.log("Is it in there? [0, 9]", isItemInArray(arr, coor1)); // True
// Test coor2
console.log("Is it in there? [1, 2]", isItemInArray(arr, coor2)); // False
// Then
if (!isItemInArray(arr, [x, y])) {
arr.push([x, y]);
}
This implementation loops and grabs every value. If you care about performance you can do more complicated things like sorting the original array by the first index and then using binary search on the first index.
Another way is to bucket the first coordinate of each item in the array in an object (like a hashtable) and bucket the second value in each of those buckets to reduce search times; more info here http://en.wikipedia.org/wiki/Bucket_sort.
Otherwise this is probably good enough for what you need.
How to find the index of a tuple in a 2D array in python?
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))
Find indices of a value in 2d matrix
If you want all of the locations that the value appears at, you can use the following list comprehension with val
set to whatever you're searching for
[(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]
for example:
>>> mymatrix=[[1,2,9],[4,9,6],[7,8,9]]
>>> val = 9
>>> [(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]
[(0, 2), (1, 1), (2, 2)]
EDIT
It's not really true that this gets all occurrences, it will only get the first occurrence of the value in a given row.
Indexing 2d arrays/lists
Here's an example of traversing a 2-dimensional array and extracting the index values for elements that match a criteria.
A couple notes:
- I used arbitrary example data since you didn't include specifics about the values you're dealing with
- I demonstrated handling duplicate values in the 2-dimensional array. Depending on your assumptions, you may need to adjust the logic (e.g. handling duplicates in
words_to translate
, maybe you usedlist.index()
because only care about the first instance, etc.)
import collections
words_list2d = [
['here', 'are', 'example'],
['words', 'in', 'a'],
['2d', 'array', 'with'],
['duplicate', 'words', 'duplicate'],
]
words_to_translate = ['example', 'array', 'duplicate', 'words']
word_indexes = collections.defaultdict(list)
for row_index, row in enumerate(words_list2d):
for value_index, value in enumerate(row):
for word in words_to_translate:
if word == value:
word_indexes[word].append((row_index, value_index))
break
for word in word_indexes:
print(f"{word}: {word_indexes[word]}")
Output:
$ python3 find_words_in_2d_array.py
example: [(0, 2)]
words: [(1, 0), (3, 1)]
array: [(2, 1)]
duplicate: [(3, 0), (3, 2)]
Get the position of the largest value in a multi-dimensional NumPy array
The argmax()
method should help.
Update
(After reading comment) I believe the argmax()
method would work for multi dimensional arrays as well. The linked documentation gives an example of this:
>>> a = array([[10,50,30],[60,20,40]])
>>> maxindex = a.argmax()
>>> maxindex
3
Update 2
(Thanks to KennyTM's comment) You can use unravel_index(a.argmax(), a.shape)
to get the index as a tuple:
>>> from numpy import unravel_index
>>> unravel_index(a.argmax(), a.shape)
(1, 0)
How to get the Index of a specific item in Multidimensional (nested) Arrays?
Try
ary.find_index { |arr| arr.include?([0, 4]) }
Related Topics
Running a Shell Command from Ruby: Capturing the Output While Displaying the Output
Load Works on Local Path, Require Doesn'T
Checking If Activerecord Find Returns a Result
Why Does Psych Yaml Interpreter Add Line Breaks Around 80 Characters
How to Print Unicode Character U-1F4A9 'Pile of Poo' Emoji
Disable Devise's :Confirmable On-The-Fly to Batch-Generate Users
Ruby on Rails Collection Select - How to Pre-Select the Right Value
Equivalent Ruby .Times in Coffeescript
Get Available Diskspace in Ruby
Combine Thumbnails to One Large Image with Rmagick
Understand "Current_User" Concept When Creating a Login Session in Ruby
How to Implement Composite Primary Keys in Rails
Ruby - Problems with Expect and Pty
How to "Nest" the Inclusion of Modules When Using the Ruby on Rails Activesupport::Concern Feature