Edin Mahmutovic
Edin Mahmutovic

Reputation: 117

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])

Upvotes: 5

Views: 6995

Answers (3)

Muhammad Hassan
Muhammad Hassan

Reputation: 14391

A simple way to do this with a native Python list is:

>> a = [1,2,3,4,1,2,1]
>> del a[a.index(min(a))]
>> a
[2, 3, 4, 1, 2, 1]

Upvotes: 1

Sumit Singh
Sumit Singh

Reputation: 9

You can simple do two things first sort and then shift array. For example

var list = [2, 1, 4, 5, 1];
list=list.sort(); // result would be like this [1,1,2,4,5]
list=list.shift();// result would be [1,2,4,5]

Upvotes: -1

Brad Solomon
Brad Solomon

Reputation: 40908

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.

Upvotes: 8

Related Questions