检查 pandas 中列之间的特定值变化

Checking for specific value change between columns in pandas

我有 4 列数值介于 1 和 4 之间,我试图查看在这 4 列中哪些行从值 1 变为值 4,从 a 列到 d 列.目前我正在计算每列之间的差异并寻找值 3。有没有更好的方法来做到这一点?

这是我要查找的内容(用 0 代替 nan):

    ID  a  b  c  d  check
    1   1  0  1  4  True
    2   1  0  1  1  False
    3   1  1  1  4  True
    4   1  3  3  4  True
    5   0  0  1  4  True
    6   1  2  3  3  False
    7   1  0  0  4  True
    8   1  4  4  4  True
    9   1  4  3  4  True 
   10   1  4  1  1  True

您可以尝试比较 apply

中 4 和 1 的索引
cols = ['a', 'b', 'c', 'd']

def get_index(lst, num):
    return lst.index(num) if num in lst else -1

df['Check'] = df[cols].apply(lambda row: get_index(row.tolist(), 4) > get_index(row.tolist(), 1), axis=1)
print(df)

   ID  a  b  c  d  check  Check
0   1  1  0  1  4   True   True
1   2  1  0  1  1  False  False
2   3  1  1  1  4   True   True
3   4  1  3  3  4   True   True
4   5  0  0  1  4   True   True
5   6  1  2  3  3  False  False
6   7  1  0  0  4   True   True
7   8  1  4  4  4   True   True
8   9  1  4  3  4   True   True

你可以cummax

col = ['a','b','c','d']
s = df[col].cummax(1)
df['new'] = s[col[:3]].eq(1).any(1) & s[col[-1]].eq(4)
Out[523]: 
0     True
1    False
2     True
3     True
4     True
5    False
6     True
7     True
8     True
dtype: bool