Skip to content Skip to sidebar Skip to footer

Remove Values From Numpy Array Closer To Each Other

Actually i want to remove the elements from numpy array which are closer to each other.For example i have array [1,2,10,11,18,19] then I need code that can give output like [1,10,1

Solution 1:

In the following is provided an additional solution using numpy functionalities (more precisely np.ediff1d which makes the differences between consecutive elements of a given array. This code considers as threshold the value associated to the th variable.

a = np.array([1,2,10,11,18,19])
th = 1
b = np.delete(a, np.argwhere(np.ediff1d(a) <= th) + 1) # [1, 10, 18]

Solution 2:

Here is simple function to find the first values of series of consecutives values in a 1D numpy array.

import numpy as np

def find_consec(a, step=1):
    vals = []
    for i, x in enumerate(a):
        if i == 0:
            diff = a[i + 1] - x
            if diff == step:
                vals.append(x)
        elif i < a.size-1:
            diff = a[i + 1] - x
            if diff > step:
                vals.append(a[i + 1])
    return np.array(vals)

a = np.array([1,2,10,11,18,19])
find_consec(a) # [1, 10, 18]

Solution 3:

Welcome to stackoverflow. below is the code that can answer you question:

def closer(arr,cozy):
    result = []
    result.append(arr[0])
    for i in range(1,len(arr)-1):
        if arr[i]-result[-1]>cozy:
            result.append(arr[i])
    print result           

Example:

a = [6,10,7,20,21,16,14,3,2]
a.sort()
closer(a,1)
output : [2, 6, 10, 14, 16, 20]
closer(a,3)
Output: [2, 6, 10, 14, 20]

Post a Comment for "Remove Values From Numpy Array Closer To Each Other"