Sorting arrays in NumPy by column

后端 未结 13 2204
既然无缘
既然无缘 2020-11-22 03:47

How can I sort an array in NumPy by the nth column?

For example,

a = array([[9, 2, 3],
           [4, 5, 6],
           [7, 0, 5]])

13条回答
  •  感情败类
    2020-11-22 04:20

    import numpy as np
    a=np.array([[21,20,19,18,17],[16,15,14,13,12],[11,10,9,8,7],[6,5,4,3,2]])
    y=np.argsort(a[:,2],kind='mergesort')# a[:,2]=[19,14,9,4]
    a=a[y]
    print(a)
    

    Desired output is [[6,5,4,3,2],[11,10,9,8,7],[16,15,14,13,12],[21,20,19,18,17]]

    note that argsort(numArray) returns the indices of an numArray as it was supposed to be arranged in a sorted manner.

    example

    x=np.array([8,1,5]) 
    z=np.argsort(x) #[1,3,0] are the **indices of the predicted sorted array**
    print(x[z]) #boolean indexing which sorts the array on basis of indices saved in z
    

    answer would be [1,5,8]

提交回复
热议问题