Home > OS >  Sort multi-dimensional string array descending without changing original array order in python?
Sort multi-dimensional string array descending without changing original array order in python?

Time:02-03

have got an array like below:

x = array([['PP Mango', 0.25, 0.75, 'PP'],
       ['PP Nectarine', 0.25, 0.75, 'PP'],
       ['Lemon', 0.25, 0.75, 'Loose'],
       ['PP Peach', 0.25, 0.75, 'PP'],
       ['Orange Navel', 0.25, 0.75, 'Loose'],
       ['PP Cherries', 0.25, 0.75, 'PP']], dtype=object)
   

I'm trying to sort this multi-dimensional array w.r.t. 4th element x[:,3] which is a string(this will be always either 'PP' or 'Loose') in descending order without changing the original row order.

Tried code:

x[x[:,3].argsort()][::-1]       #but this shuffles the original array row order within 4th element which should not happen

Expected Output:

x = array([['PP Mango', 0.25, 0.75, 'PP'],
       ['PP Nectarine', 0.25, 0.75, 'PP'],
       ['PP Peach', 0.25, 0.75, 'PP'],
       ['PP Cherries', 0.25, 0.75, 'PP'],
       ['Lemon', 0.25, 0.75, 'Loose'],
       ['Orange Navel', 0.25, 0.75, 'Loose']], dtype=object)

CodePudding user response:

Use list sort with just a sort key which compares if 4th element is "Loose".

Stability of python sort guarantees that it's not going to move elements around if not needed.

lst = [['PP Mango', 0.25, 0.75, 'PP'],
       ['PP Nectarine', 0.25, 0.75, 'PP'],
       ['Lemon', 0.25, 0.75, 'Loose'],
       ['PP Peach', 0.25, 0.75, 'PP'],
       ['Orange Navel', 0.25, 0.75, 'Loose'],
       ['PP Cherries', 0.25, 0.75, 'PP']]

lst = sorted(lst,key=lambda x:x[3]=='Loose')
print(lst)

prints:

[['PP Mango', 0.25, 0.75, 'PP'], 
['PP Nectarine', 0.25, 0.75, 'PP'], 
['PP Peach', 0.25, 0.75, 'PP'], 
['PP Cherries', 0.25, 0.75, 'PP'], ['Lemon', 0.25, 0.75, 'Loose'],
 ['Orange Navel', 0.25, 0.75, 'Loose']]

This is a non-numpy solution, but it works. Then convert back to numpy array: array(lst)

CodePudding user response:

You just need to use a sorting key, i.e. specify what the sorting algorithm is oging to comapre when trying to sort the elements of your array. Here you want the key to be the last element of each row, so:

np.array(sorted(x, key= lambda element: element[3], reverse=True))

should give you your desired output. Note the use of reverse=True to get the data in reversed order.

  • Related