NumPy, pandas, and Python native sorting methods __python

Source: Internet
Author: User

in the NumPy:

Argsort returns the sorted index, which can be sorted accordingly.

#---------One-dimensional case--------------
Values=np.random.permutation (a)  #产生0到9的一个排列
Values
OUT[758]: Array ([6, 7, 0, 9, 5, 2, 4, 3, 8, 1])
  
Indexer=np.argsort (values) #返回排序后的values的index
Indexer
OUT[761]: Array ([2, 9, 5, 7, 6, 4, 0, 1, 8, 3], Dtype=int64)
Values[indexer] #升序排列
OUT[762]: Array ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
VALUES[INDEXER][::-1] #降序排列
OUT[763]: Array ([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
#----------------Two-dimensional situation-----------
Arr=np.random.randn. Reshape (4,5)
Arr
Array ([[0.06508931,  0.56513883,  0.62546144,-1.28835261,-2.08906088],
[1.5425056,  0.69033553,  1.60385421,-1.52568607,-0.41737589],
[ -0.91894216,  2.08802511,-0.70341454,-0.08491163,-0.17903858],
[ -0.3333518, -0.49513354,  1.56342694,  0.92744459,  0.48037342]]
Arr[:,np.argsort (Arr[2])] # from the 2nd line from small to large arrangement
Array ([[0.06508931,  0.62546144, -2.08906088, -1.28835261,  0.56513883],
[1.5425056,  1.60385421, -0.41737589, -1.52568607,  0.69033553],
[ -0.91894216, -0.70341454, -0.17903858, -0.08491163,  2.08802511],
[ -0.3333518,  1.56342694,  0.48037342,  0.92744459,-0.49513354]]
Arr[np.argsort (arr[:,0]),:] # from the No. 0 column from small to large arrangement
Array ([[ -0.91894216,  2.08802511,-0.70341454,-0.08491163,-0.17903858],
[ -0.3333518, -0.49513354,  1.56342694,  0.92744459,  0.48037342],
[0.06508931,  0.56513883,  0.62546144,-1.28835261,-2.08906088],
[1.5425056,  0.69033553,  1.60385421,-1.52568607,-0.41737589]]

in the Pandas

By using the Sort_index or Sort_values method, the default sort on the Axis=0 (that is, sorted by the size of a column) can be changed to one row by Axis=1. By=index,index is the index of the column or row that you want to sort.

Frame=dataframe (arr)
Frame
Frame.sort_index (by=0,ascending=false) # is sorted according to the value in column No. 0, in descending order.
  
Related Article

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.