Pandas 检查多列的条件并减去 1

Fla*_*ane 3 python dataframe pandas

我创建了以下 Dataframe(实际上有 1000 多行和 20 多列):

d = {'col1': [0, 0, 4, 6], 'col2': [3, 4, 0, 0], 'col3': [0, 10, 0, 0], 'END': [0, 0, 0, 0]}
df = pd.DataFrame(data=d)
print(df)

Out:
   col1  col2  col3  END
0     0     3     0    0
1     0     4    10    0
2     4     0     0    0
3     6     0     0    0
Run Code Online (Sandbox Code Playgroud)

现在我想按索引为每一列创建一个循环来执行以下操作:检查该列中的当前项目是否大于 0,如果是,则检查右侧旁边的列中的项目是否等于 0。为 true,则从该列中的项目中减去 1,然后移动到下一列并重复。

到目前为止,我最好的尝试是使用 while 循环来查找正确的字段:

Counter = len(list(df))
i = 0
while 0 < Counter:
    if df.iloc[:,i] > 0 and df.iloc[:,i+1] == 0:
        df.iloc[:,i] - 1
    i = i +1
Run Code Online (Sandbox Code Playgroud)

然而,此代码会引发值错误。

我想要的结果如下所示:

   col1  col2  col3  END
0     0     2     0    0
1     0     4     9    0
2     3     0     0    0
3     5     0     0    0
Run Code Online (Sandbox Code Playgroud)

小智 8

这应该相当快:

df[df.ne(0) & df.shift(-1, axis=1).eq(0)] -= 1
Run Code Online (Sandbox Code Playgroud)

输出:

>>> df
   col1  col2  col3  END
0     0     2     0    0
1     0     4     9    0
2     3     0     0    0
3     5     0     0    0
Run Code Online (Sandbox Code Playgroud)