Search code examples
pythonnumpysortingis-empty

How make np.argsort place empty strings at the END of an array instead of at the beginning


I'm honestly surprised that this question hasn't come up on the forums (at least from what I have seen) earlier. Anyway, I am currently attempting to sort a list of strings, many of which are empty, in alphabetic fashion using np.argsort like so:

list = [ "Carrot", "Star", "Beta", "Zoro" , ""]

Right now, any call of np.argsort(list) will return the following array of indices:

[4,2,0,1,3] # => ["", "Beta", "Carrot", "Star", "Zoro"]

Is there a way to specify the order of the argsort function so that the empty strings are placed at the end of the array like so:

[2,0,1,3,4] # => ["Beta", "Carrot", "Star", "Zoro", ""]

Any input will be greatly appreciated!


Solution

  • One simple way of getting the order you want would be using np.roll:

    lst = [ "Carrot", "Star", "Beta", "Zoro" , ""]
    arr = np.array(lst)
    idx = np.roll(arr.argsort(),np.count_nonzero(arr))
    arr[idx]
    # array(['Beta', 'Carrot', 'Star', 'Zoro', ''], dtype='<U6')