Delete similar values in an array python numpy

Question:

Is there an easy possibility to delete similar values in an array (with condition) without using a for loop? For example lets say I have an array

np.array([1.2, 3.4, 3.5, 8.9, 10.9])

In this case, i would set the condition for example difference < 0.3 and get as an output

np.array([1.2, 3.4, 8.9, 10.9])

I haven’t seen anything on the internet similar to this question. Of course there is the function .unique() but that is only for exactly the same values.

Asked By: Hrvoje Krizic

||

Answers:

If you want to delete the successive values, you can compute the successive differences and perform boolean indexing:

a = np.array([1.2, 3.4, 3.5, 8.9, 10.9])

out = a[np.r_[True, np.diff(a)>=0.3]]

Or, if you want the absolute difference:

out = a[np.r_[True, np.abs(np.diff(a))>=0.3]]

Output:

array([ 1.2,  3.4,  8.9, 10.9])

Intermediates:

np.diff(a)
# array([2.2, 0.1, 5.4, 2. ])

np.diff(a)>=0.3
# array([ True, False,  True,  True])

np.r_[True, np.diff(a)>=0.3]
# array([ True,  True, False,  True,  True])
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.