重复 B 列中的值,直到 A 列中发生变化

Repeat the value in column B until there is a change in column A

我需要在 B 列中重复该值,直到 A 列中发生更改。

这是输入

    Column A  Column B
     18         1
     18         0
     18         0
     18         0
     24         2
     24         0
     18         3
     18         0
     18         0
     18         0

预期产出

   Column A  Column B
    18         1
    18         1
    18         1
    18         1
    24         2
    24         2
    18         3
    18         3
    18         3
    18         3

您可以使用移位列 Col Atransform by first if need repeat first value of each group by Series which is create by cumsum:

print (df['Col A'].ne(df['Col A'].shift()).cumsum())
0    1
1    1
2    1
3    1
4    2
5    2
6    3
7    3
8    3
9    3
Name: Col A, dtype: int32

df['Col B'] = df.groupby(df['Col A'].ne(df['Col A'].shift()).cumsum())['Col B']
                .transform('first')
print (df)
   Col A  Col B
0     18      1
1     18      1
2     18      1
3     18      1
4     24      2
5     24      2
6     18      3
7     18      3
8     18      3
9     18      3
A =[18,18,18,18,24,24,18,18,18,18]
def func(A):
    B = []
    b = 1
    for i in range(len(A)):
        if i == 0:
            B.append(b)
            continue
        if A[i] != A[i-1]:
            b += 1
            B.append(b)          
        else:
            B.append(b)
    return B

输出:

[1, 1, 1, 1, 2, 2, 3, 3, 3, 3]