如何将标志值之前的n-1值设置为-1,因为我需要删除标志值之前的n-1值例如,如果标志值为4,则需要将前3行设置为-1。
示例表
UID | exclusion_flag | 1 bop2uc-1 | 0 |
---|---|
1 bop2uc-2 | 0 |
1 bop2uc-3 | 0 |
1 bop2uc-4 | 4 |
1 bop2uc-5 | 0 |
1 bop2uc-6 | 0 |
1 bop2uc-7 | 0 |
1 bop2uc-8 | 2 |
1 bop2uc-9 | 0 |
1 bop2ud-1 | 0 |
1 bop2ud-2 | 0 |
1 bop2ud-3 | 0 |
1 bop2ud-4 | 0 |
1 bop2ud-5 | 4 |
我不知道问题是否仍然存在,但这是我的解决方案:
- 我初始化代表计数器的
mem
变量 我使用 - 如果实际值大于零,我想用实际值覆盖
mem
,否则,mem -1
。我不希望counter为负,因此max(0, mem-1)
. - 如果
mem
大于0,则表示我们仍在计算行数,将row标记为-1。 - 如果
mem
等于x
,这是我们的计数器序列开始的行,我们希望在out
之外保留x
。 - 我以正确的顺序返回
out_arr
。
reversed
函数反向迭代列表。
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