Show Sidebar Hide Sidebar


How to generate an array of indices to sort a NumPy array.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!


This tutorial imports Plotly and Numpy.

In [1]:
import plotly.plotly as py
from import FigureFactory as FF

import numpy as np


np.argsort() is helpful if you have an array of values which is unsorted. It returns an array where each element value represents an index value pointing of the original array. If these indices are replaced by the corresponding element found in the original array, the resulting array will be sorted!

For example, the original array may look like

$$ \begin{align*} [4,1,3,2] \end{align*} $$

and the array of indices from np.argsort() would look like

$$ \begin{align*} [1,3,2,0] \end{align*} $$

and to construct the sorted array, we have array[1] which points to the value $1$ in the original array, array[3], which points to $2$ in the original, etc.

In [2]:
import plotly.plotly as py
from import FigureFactory as FF

array = np.array([4, 6, 5, 2, 3, 7, 9, 8, 0, 1])

fig = FF.create_annotated_heatmap([array], colorscale='Blues')
fig.layout.title = 'Unsorted Array'
py.iplot(fig, filename='numpy-argsort-unsorted')
In [3]:
import plotly.plotly as py
from import FigureFactory as FF

indices = np.argsort(array)
sorted_array = [array[indices[j]] for j in range(len(array))]

fig = FF.create_annotated_heatmap([sorted_array], colorscale='Blues')
fig.layout.title = 'Sorted Array'
py.iplot(fig, filename='numpy-argsort-sorted')
In [2]:
Help on function argsort in module numpy.core.fromnumeric:

argsort(a, axis=-1, kind='quicksort', order=None)
    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.
    a : array_like
        Array to sort.
    axis : int or None, optional
        Axis along which to sort.  The default is -1 (the last axis). If None,
        the flattened array is used.
    kind : {'quicksort', 'mergesort', 'heapsort'}, optional
        Sorting algorithm.
    order : str or list of str, optional
        When `a` is an array with fields defined, this argument specifies
        which fields to compare first, second, etc.  A single field can
        be specified as a string, and not all fields need be specified,
        but unspecified fields will still be used, in the order in which
        they come up in the dtype, to break ties.
    index_array : ndarray, int
        Array of indices that sort `a` along the specified axis.
        If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.
    See Also
    sort : Describes sorting algorithms used.
    lexsort : Indirect stable sort with multiple keys.
    ndarray.sort : Inplace sort.
    argpartition : Indirect partial sort.
    See `sort` for notes on the different sorting algorithms.
    As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
    nan values. The enhanced sort order is documented in `sort`.
    One dimensional array:
    >>> x = np.array([3, 1, 2])
    >>> np.argsort(x)
    array([1, 2, 0])
    Two-dimensional array:
    >>> x = np.array([[0, 3], [2, 2]])
    >>> x
    array([[0, 3],
           [2, 2]])
    >>> np.argsort(x, axis=0)
    array([[0, 1],
           [1, 0]])
    >>> np.argsort(x, axis=1)
    array([[0, 1],
           [0, 1]])
    Sorting with keys:
    >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
    >>> x
    array([(1, 0), (0, 1)],
          dtype=[('x', '<i4'), ('y', '<i4')])
    >>> np.argsort(x, order=('x','y'))
    array([1, 0])
    >>> np.argsort(x, order=('y','x'))
    array([0, 1])

Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.