Home > Backend Development > Python Tutorial > How to sort a two-dimensional array according to a row or column in Python

How to sort a two-dimensional array according to a row or column in Python

黄舟
Release: 2018-05-11 15:49:44
Original
6296 people have browsed it

This article mainly introduces Python's method of sorting two-dimensional arrays according to a certain row or column. It analyzes the common operating techniques of Python using the lexsort method of the numpy module to sort two-dimensional arrays based on specific examples. Friends who need it You can refer to the following

The example of this article describes how Python implements the method of sorting a two-dimensional array according to a certain row or column. Share it with everyone for your reference, the details are as follows:

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

(Corresponding to lexsort one-dimensional array is argsort a.argsort()You can use it this way; argsort does not modify the original array and returns the index)

The default is to press the last The elements in a row are sorted from small to large, and the index position of the last row of elements after sorting is returned.

Suppose array a, the returned index ind, ind returns a one-dimensional array

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

For two-dimensional arrays, detailed examples will be given below.

import numpy as np
>>> a
array([[ 2, 7, 4, 2],
    [35, 9, 1, 5],
    [22, 12, 3, 2]])
Copy after login

Sort by last column order

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

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]])
Copy after login

By first column Sort in order

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

Sort in order of the last row

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

Sort in order of the first row

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

The above is the detailed content of How to sort a two-dimensional array according to a row or column in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template