How to get indices of a sorted array in Python
python argsort descending
numpy sort array by another array
numpy sort descending
python sort while keeping index
sort two arrays based on one python
the function that returns the indices of the sorted elements.
I have a numerical list:
myList = [1, 2, 3, 100, 5]
Now if I sort this list to obtain
[1, 2, 3, 5, 100].
What I want is the indices of the elements from the
original list in the sorted order i.e.
[0, 1, 2, 4, 3]
--- ala MATLAB's sort function that returns both
values and indices.
If you are using numpy, you have the argsort() function available:
>>> import numpy >>> numpy.argsort(myList) array([0, 1, 2, 4, 3])
This returns the arguments that would sort the array or list.
how to return index of a sorted list?, You can use the python sorting functions' key parameter to sort the index array instead. >>> s = [2, 3, 1, 4, 5] >>> sorted(range(len(s)), key=lambda k: s[k]) [2, 0, NumPy: Get the indices of the sorted elements of a given array. NumPy Sorting and Searching: Exercise-5 with Solution. Write a NumPy program to get the indices of the sorted elements of a given array.
Something like next:
>>> myList = [1, 2, 3, 100, 5] >>> [i for i in sorted(enumerate(myList), key=lambda x:x)] [0, 1, 2, 4, 3]
enumerate(myList) gives you a list containing tuples of (index, value):
[(0, 1), (1, 2), (2, 3), (3, 100), (4, 5)]
You sort the list by passing it to
sorted and specifying a function to extract the sort key (the second element of each tuple; that's what the
lambda is for. Finally, the original index of each sorted element is extracted using the
[i for i in ...] list comprehension.
numpy.argsort, argsort. Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order. This function in numpy returns the indices of the sorted array instead of the array elements. In the below example we take the array, print its elements along with the index for each element. Then we apply the argsort function which gives us the indices of sorted array as a result and the result is also an array.
myList = [1, 2, 3, 100, 5] sorted(range(len(myList)),key=myList.__getitem__) [0, 1, 2, 4, 3]
Python, Python | Returning index of a sorted list. Sort a list in python and then return the index of elements in sorted order. Examples: s = numpy.array([ 2 , 3 , 1 , 4 , 5 ]). What is a Structured Numpy Array and how to create and sort it in Python? How to sort a Numpy Array in Python ? Python Numpy : Select an element or sub array by index from a Numpy Array; numpy.arange() : Create a Numpy Array of evenly spaced numbers in Python; How to get Numpy Array Dimensions using numpy.ndarray.shape & numpy.ndarray.size() in
The answers with
enumerate are nice, but I personally don't like the lambda used to sort by the value. The following just reverses the index and the value, and sorts that. So it'll first sort by value, then by index.
sorted((e,i) for i,e in enumerate(myList))
numpy.argsort() in Python, Return : [index_array, ndarray] Array of indices that sort arr along the specified axis.If arr is one-dimensional then arr[index_array] returns a sorted arr. Code #1 :. An overview on how to sort a list, tuple or object in Python, using the built-in sorted method. You can set the sort algorithm, or sort your own objects.
Updated answer with
sorted(enumerate(a), key=lambda x: x) # [(0, 1), (1, 2), (2, 3), (4, 5), (3, 100)]
Zip the lists together: The first element in the tuple will the index, the second is the value (then sort it using the second value of the tuple
x, x is the tuple)
itemgetter from the
from operator import itemgetter sorted(enumerate(a), key=itemgetter(1))
Python sorted() Function, () function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as arr that that would sort the array. One option could be to map the list of objects to a list of tuples [obj1, obj2, ] -> [(0,obj1), (1, obj2), ] and sort this list. Then you have the new order of the original indexes right away. You don't really need the indices to sort the corresponding list.
numpy - Get the index order that would sort an array, a list that contains BOTH string values AND numeric values. numpy.argsort¶ numpy.argsort (a, axis=-1, kind=None, order=None) [source] ¶ Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.
NumPy: Get the indices of the sorted elements of a given array , Python code example 'Get the index order that would sort an array' for the package numpy, powered by Kite. >>> ["foo", "bar", "baz"].index("bar") 1 Reference: Data Structures > More on Lists Caveats follow. Note that while this is perhaps the cleanest way to answer the question as asked, index is a rather weak component of the list API, and I can't remember the last time I used it in anger.
Sorting Arrays, NumPy: Get the indices of the sorted elements of a given array. Sample Solution: Python Code: import numpy as np student_id = np.array([1023, 5202, 6230, 1671, 1682, 5241, 4532]) print("Original array:") print(student_id) i = np.argsort(student_id) print("Indices of the sorted elements of a given array:") print(i) First, the initial list is decorated with new values that control the sort order. Second, the decorated list is sorted. Finally, the decorations are removed, creating a list that contains only the initial values in the new order. For example, to sort the student data by grade using the DSU approach:
- Related: stackoverflow.com/questions/7851077/…
- @unutbu This is not a dupe (IMO). The question does not contradict using Numpy.argsort()
- @amit: What do you mean by "does not contradict"?
- @unutbu Numpy.argsort() is a fine answer to this question, it might be a dupe to the other thread linked (which you also closed and I thin you shouldn't have) but not to the one you mentioned, as Numpy.argsort() is fine answer for these two, but NOT for the one you refered to.
- Unfortunately, this question has a severe flaw in its choice of example, as two different ways of reading the question would give the same answer when the input is just a transposition out of sorted order.
- Note that this may not be what you want! See this question: stackoverflow.com/questions/54388972/…
- you can use
itemgetter(1)instead of the lambda function
- @gnibbler is referring to the
itemgetterfunction in the
operatormodule, FYI. So do
from operator import itemgetterto use it.
- you can get the sorted list and indicies by using zip:
sorted_items, sorted_inds = zip(*sorted([(i,e) for i,e in enumerate(my_list)], key=itemgetter(1)))
- @RomanBodnarchuk this doesn't work,
x = [3,1,2]; numpy.argsort(x)yields [1,2,0].
- This answer was discussed on meta.
- enumerate seems more appropriate than zip in this case