Checking if values of a row are consecutive

Viewed 834

I have a df like this:

     1   2   3   4   5   6
0    5  10  12  35  70  80
1   10  11  23  40  42  47
2    5  26  27  38  60  65

Where all the values in each row are different and have an increasing order.

I would like to create a new column with 1 or 0 if there are at least 2 consecutive numbers. For example the second and third row have 10 and 11, and 26 and 27. Is there a more pythonic way than using an iterator? Thanks

1 Answers

Use DataFrame.diff for difference per rows, compare by 1, check if at least one True per rows and last cast to integers:

df['check'] = df.diff(axis=1).eq(1).any(axis=1).astype(int)
print (df)
    1   2   3   4   5   6  check
0   5  10  12  35  70  80      0
1  10  11  23  40  42  47      1
2   5  26  27  38  60  65      1

For improve performance use numpy:

arr = df.values
df['check'] = np.any(((arr[:, 1:] - arr[:, :-1]) == 1), axis=1).astype(int)
Related