Search code examples
pythonarrayspython-3.xnumpyminimum

How to delete the lowest number in an array, and if there's several minimum numbers, delete the first


I'm trying to make a script, where the input is an array with random numbers. I try to delete the lowest number in the array which is no problem. But if there are several occurrences of this number in the array, how do I make sure that it is only the first occurrence of this number that gets deleted?

Let's say we have the following array:

a = np.array([2,6,2,1,6,1,9])

Here the lowest number is 1, but since it occurs two times, I only want to remove the first occurence so i get the following array as a result:

 a = np.array([2,6,2,6,1,9])

Solution

  • Since you're using NumPy, not native Python lists:

    a = np.array([2,6,2,1,6,1,9])
    
    a = np.delete(a, a.argmin())
    
    print(a)
    # [2 6 2 6 1 9]
    

    np.delete: Return a new array with sub-arrays along an axis deleted.

    np.argmin: Returns the indices of the minimum values along an axis.

    With a NumPy array, you cannot delete elemensts with del as you can in a list.