Jan
Jan

Reputation: 1479

Group a list of float with near number, regard its near position in np.array

I read this question and adapt to my purpose. I want to group floats with their near numbers. Between the numbers next to each other should have less than 1 but the first and last in group can be more than 1.

The array cannot be sorted. If the difference between two values is less than 1 but their positions in array are far from each other, they have to be in different group.

I got wrong result from this code.

d = np.array([[100.1,100.6,101.1,500,500.3,500.6,500.9,44.1,44.2,101.9,102.1],[40,41]])

ans = []
for i in range(d.size):     
    m = [[d[i][0]]]     
    for x in d[i][1:]:
        if x - m[-1][0] < 1:
            m[-1].append(x)
        else:
            m.append([x])
    ans.append(m)
print ans
>>[[[100.1, 100.6], [101.1], [500, 500.3, 500.6, 500.9, 44.1, 44.2, 101.9, 102.1]], [[40], [41]]]

The expected ans should be

[[[100.1, 100.6, 101.1], [500, 500.3, 500.6, 500.9], [44.1, 44.2],[101.9, 102.1]], [[40], [41]]]]

What did I do wrong here?

Upvotes: 0

Views: 626

Answers (1)

Divakar
Divakar

Reputation: 221634

If you are open to an alternative more efficient solution, here's one using NumPy's np.split -

[np.split(i, np.flatnonzero(np.abs(np.diff(i))>=1)+1) for i in d]

Sample run -

In [83]: d
Out[83]: 
array([[100.1, 100.6, 101.1, 500, 500.3, 500.6, 500.9, 44.1, 44.2, 101.9, 102.1],
       [40, 41]], dtype=object)

In [84]: [np.split(i, np.flatnonzero(np.abs(np.diff(i))>=1)+1) for i in d]
Out[84]: 
[[array([ 100.1,  100.6,  101.1]),
  array([ 500. ,  500.3,  500.6,  500.9]),
  array([ 44.1,  44.2]),
  array([ 101.9,  102.1])],
 [array([40]), array([41])]]

Upvotes: 2

Related Questions