检查行的值是否连续

Joe*_*Joe 3 python dataframe pandas

我有这样的df:

     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
Run Code Online (Sandbox Code Playgroud)

其中每行中的所有值都不同并且具有递增的顺序.

我想创建一个新列,1或者0如果至少有2个连续数字.例如,第二行和第三行有1011,2627.有没有比使用迭代器更pythonic的方式?谢谢

jez*_*ael 8

使用DataFrame.diff每行的差异,比较1,检查True每行至少一个,最后一次是否转换为整数:

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
Run Code Online (Sandbox Code Playgroud)

为了提高性能使用numpy:

arr = df.values
df['check'] = np.any(((arr[:, 1:] - arr[:, :-1]) == 1), axis=1).astype(int)
Run Code Online (Sandbox Code Playgroud)

  • `df.eq(df.shift(axis = 1)+1).any(1).astype(int)` (3认同)