Home > Back-end >  how to compare current and last element iterated from numpy without loop
how to compare current and last element iterated from numpy without loop

Time:01-03

In 2d array get the last column and compare current value with its last iterated value and if the difference is == 1 then get row indexes of both of them . I able to do it using for loop but it gets slow when array grows as there are multiple conditions next after getting indexes

x=np.array ([[79, 50, 18, 55, 35], 
            [46, 71, 46, 95, 80], #1
            [97, 37, 71,  2, 79], #2
            [80, 96, 60, 85, 72],
            [ 6, 52, 63, 86, 38],
            [35, 50, 13, 93, 54], #5
            [69, 21,  4, 40, 53], #6           
            [18, 34, 91, 67, 89],
            [82, 16, 16, 24, 80]])

last_column = x[:,[-1]]
for kkk in range(1,len(last_column)):
    if last_column[kkk] == last_column[kkk-1]   1 \ 
    or last_column[kkk] == last_column[kkk-1] - 1 :
        print('range',last_column[kkk],last_column[kkk-1])

ouput is -
[80]
[79]
range [79] [80]
[72]
[38]
[54]
[53]
range [53] [54]
[89]
[80]

CodePudding user response:

I don't think there is a way of doing this in python that doesn't use a loop (or a function that utilizes a loop). But I would suggest something like this, it worked quite well for me:

import numpy as np

x = np.array([[79, 50, 18, 55, 35], [46, 71, 46, 95, 80], [97, 37, 71, 2, 79],[80, 96, 60, 85, 72], [ 6, 52, 63, 86, 38], [35, 50, 13, 93, 54], [69, 21,  4, 40, 53], [18, 34, 91, 67, 89], [82, 16, 16, 24, 80]])

last_column = x[:,-1]

for kkk in range(1,len(last_column)):
    if abs(last_column[kkk] - last_column[kkk-1]) == 1:
        print('range',last_column[kkk],last_column[kkk-1])

This performed quite well on my device in about, 0.00023s possibly less.

CodePudding user response:

You can use np.diff to compute the difference between all the numbers, and select those that are 1 or -1, and use np.pad to shift the resulting mask to get the n-1 items, and finally zip them together:

diff = np.insert(np.diff(x[:, -1]), 0, 0)
ix = (diff == -1) | (diff == 1)
z = zip(x[:,-1][ix], x[:,-1][np.pad(ix, (0,1))[1:]])

for first, second in z:
    print('range', first, second)

Output:

range 79 80
range 53 54
  • Related