Implementation of a two-dimensional array sorted by a row or column in Python

Source: Internet
Author: User
This article mainly describes the Python implementation of a two-dimensional array in accordance with a row or column of the method, combined with a specific example of Python using the Lexsort method of the NumPy module for two-dimensional array to sort the common operation skills, the need for friends can refer to the next

This example describes how Python implements a two-dimensional array to sort by a row or column. Share to everyone for your reference, as follows:

Lexsort supports the ordering of arrays in the order of specified rows or columns; is an indirect sort, lexsort does not modify the original array and returns the index.

(corresponding to the Lexsort one-dimensional array is argsort a.argsort() so used, Argsort also does not modify the original array, return index)

By default, the last line element has a small to large sort, which returns the position of the last row of elements after the index is sorted.

Sets the array A, the returned index Ind,ind returns a one-dimensional array

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

For a two-dimensional array, an example is detailed below.

Import NumPy as Np>>> aarray ([[2, 7, 4, 2],    [+, 9, 1, 5],    [22, 12, 3, 2]])

Sort by the last column order

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

Sort by the last column in reverse order

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

Sort by first column order

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

Sort by last line order

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

Sort by first row order

>>> A.t[np.lexsort (a[::-1,:])]. Tarray ([[2, 2, 4, 7],    [5, +, 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.