如何设置标志为-1 n-1行之前的一个单元格在python(下降)?



如何将标志值之前的n-1值设置为-1,因为我需要删除标志值之前的n-1值例如,如果标志值为4,则需要将前3行设置为-1。

示例表

tbody> <<tr>
UID exclusion_flag
1 bop2uc-10
1 bop2uc-20
1 bop2uc-30
1 bop2uc-44
1 bop2uc-50
1 bop2uc-60
1 bop2uc-70
1 bop2uc-82
1 bop2uc-90
1 bop2ud-10
1 bop2ud-20
1 bop2ud-30
1 bop2ud-40
1 bop2ud-54

我不知道问题是否仍然存在,但这是我的解决方案:

  1. 我初始化代表计数器的mem变量
  2. 我使用reversed函数反向迭代列表。
  3. 如果实际值大于零,我想用实际值覆盖mem,否则,mem -1。我不希望counter为负,因此max(0, mem-1).
  4. 如果mem大于0,则表示我们仍在计算行数,将row标记为-1。
  5. 如果mem等于x,这是我们的计数器序列开始的行,我们希望在out之外保留x
  6. 我以正确的顺序返回out_arr

from typing import List
import pandas as pd
dummy_col = [0, 0, 0, 0, 4, 0, 0, 0, 2]
df = pd.DataFrame(dict(col1=dummy_col))

def fun(arr: List[int]) -> List[int]:
mem = 0
out_arr = []
for x in reversed(arr):
mem = x if x > 0 else max(0, mem - 1)
out = -1 if mem > 0 else 0
out = x if mem == x else out
out_arr += [out]
return list(reversed(out_arr))

df['final_col'] = fun(arr=df['col1'].to_list())
print(df)

输出:

col1  final_col
0     0          0
1     0         -1
2     0         -1
3     0         -1
4     4          4
5     0          0
6     0          0
7     0         -1
8     2          2

相关内容

最新更新