Home > Mobile >  Sort a numpy array by frequency of element in a column in Python?
Sort a numpy array by frequency of element in a column in Python?

Time:01-30

I need to sort a multidimensional array based upon the frequency of element by given column.Below is my code:-

array=np.random.randint(0,10,[10,10])
vals, counts = np.unique(myarray[:, 0], return_counts=True)
c = np.unique(array[:, 0], return_counts=True)

res = array[np.lexsort(array, np.array(c))]

Input :-

[[1 2 4 4 3 2 2 3 2 2]
 [7 0 8 4 5 5 1 1 3 2]
 [4 6 7 1 0 8 3 9 0 9]
 [2 2 2 9 1 4 1 5 5 8]
 [3 3 1 8 0 3 9 2 2 7]
 [4 7 8 7 7 1 3 1 5 1]
 [4 4 9 5 1 4 5 6 2 6]
 [3 1 9 3 5 2 9 0 2 4]
 [8 8 2 4 3 4 8 6 0 0]
 [7 8 4 5 6 3 2 9 4 7]]

Expected result:-

array([[1, 2, 4, 4, 3, 2, 2, 3, 2, 2],
       [2, 2, 2, 9, 1, 4, 1, 5, 5, 8],
       [8, 8, 2, 4, 3, 4, 8, 6, 0, 0],
       [7, 8, 4, 5, 6, 3, 2, 9, 4, 7],
       [7, 0, 8, 4, 5, 5, 1, 1, 3, 2],
       [3, 1, 9, 3, 5, 2, 9, 0, 2, 4],
       [3, 3, 1, 8, 0, 3, 9, 2, 2, 7],
       [4, 4, 9, 5, 1, 4, 5, 6, 2, 6],
       [4, 7, 8, 7, 7, 1, 3, 1, 5, 1],
       [4, 6, 7, 1, 0, 8, 3, 9, 0, 9]])

I am getting below error :-

only integer scalar arrays can be converted to a scalar index

CodePudding user response:

np.lexsort on the counts for each element and the selected column

import numpy as np

np.random.seed(20)
array = np.random.randint(10, 20, [10, 10])
# array([[13, 19, 14, 16, 17, 12, 10, 16, 18, 15],
#        [13, 10, 16, 16, 10, 19, 15, 17, 15, 12],
#        [16, 19, 13, 13, 19, 10, 16, 12, 13, 11],
#        [18, 10, 12, 17, 16, 16, 18, 12, 11, 13],
#        [12, 16, 19, 14, 16, 14, 18, 16, 12, 13],
#        [11, 15, 12, 11, 18, 12, 14, 14, 18, 16],
#        [10, 13, 14, 10, 15, 16, 19, 17, 14, 10],
#        [16, 11, 19, 16, 17, 19, 17, 16, 19, 18],
#        [18, 12, 12, 11, 15, 12, 19, 17, 15, 15],
#        [19, 16, 19, 19, 15, 12, 19, 16, 11, 18]])

_, inverse, counts = np.unique(array[:,0], return_counts=True, return_inverse=True)
array[np.lexsort((array[:,0], counts[inverse]))]

Output

array([[10, 13, 14, 10, 15, 16, 19, 17, 14, 10],
       [11, 15, 12, 11, 18, 12, 14, 14, 18, 16],
       [12, 16, 19, 14, 16, 14, 18, 16, 12, 13],
       [19, 16, 19, 19, 15, 12, 19, 16, 11, 18],
       [13, 19, 14, 16, 17, 12, 10, 16, 18, 15],
       [13, 10, 16, 16, 10, 19, 15, 17, 15, 12],
       [16, 19, 13, 13, 19, 10, 16, 12, 13, 11],
       [16, 11, 19, 16, 17, 19, 17, 16, 19, 18],
       [18, 10, 12, 17, 16, 16, 18, 12, 11, 13],
       [18, 12, 12, 11, 15, 12, 19, 17, 15, 15]])
  •  Tags:  
  • Related