Using Python to sort two-dimensional arrays by rows or columns [numpy lexsort] And numpylexsort

Source: Internet
Author: User

Using Python to sort two-dimensional arrays by rows or columns [numpy lexsort] And numpylexsort

This example describes how to sort two-dimensional arrays by rows or columns in Python. We will share this with you for your reference. The details are as follows:

Lexsort supports sorting arrays by specified rows or columns. It is indirect sorting. lexsort does not modify the original array and returns an index.

(Corresponding to the lexsort one-dimensional array isargsort a.argsort()In this way, you can use argsort without modifying the original array and returning the index)

By default, elements in the last row are sorted in ascending order, and the index location is returned after the last element is sorted.

Set array a and Return Index ind. ind returns a one-dimensional array.

For a one-dimensional array, a [ind] is the sorted array.

The following is an example of a two-dimensional array.

import numpy as np>>> aarray([[ 2, 7, 4, 2],    [35, 9, 1, 5],    [22, 12, 3, 2]])

Sort by the order of the last column

>>> a[np.lexsort(a.T)]array([[22, 12, 3, 2],    [ 2, 7, 4, 2],    [35, 9, 1, 5]])

Sort by last column in reverse order

>>>a[np.lexsort(-a.T)]array([[35, 9, 1, 5],    [ 2, 7, 4, 2],    [22, 12, 3, 2]])

Sort by the first column

>>> a[np.lexsort(a[:,::-1].T)]array([[ 2, 7, 4, 2],    [22, 12, 3, 2],    [35, 9, 1, 5]])

Sort by the last line

>>> a.T[np.lexsort(a)].Tarray([[ 2, 4, 7, 2],    [ 5, 1, 9, 35],    [ 2, 3, 12, 22]])

Sort by the first line

>>> a.T[np.lexsort(a[::-1,:])].Tarray([[ 2, 2, 4, 7],    [ 5, 35, 1, 9],    [ 2, 22, 3, 12]])

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.