填充等于值的列,直到另一个值 - Pandas

Fill cols where equal to value, until another value - Pandas

我正在尝试 ffill() 基于单独列的 df 中两列中的值。我希望继续填充直到满足条件。使用下面的 df,其中 Val1Val2 等于 C,我想填充后续行,直到 Code 中的字符串以 [=20] 开头=].

import pandas as pd
import numpy as np

df = pd.DataFrame({   
    'Code' : ['CA','GA','YA','GE','XA','CA','YA','FR','XA'],             
    'Val1' : ['A','B','C','A','B','C','A','B','C'],                 
    'Val2' : ['A','B','C','A','B','C','A','B','C'],
   })

mask = (df['Val1'] == 'C') & (df['Val2'] == 'C')

cols = ['Val1', 'Val2']

df[cols] = np.where(mask, df[cols].ffill(), df[cols])

预期输出:

  Code Val1 Val2
0   CA    A    A
1   GA    B    B
2   YA    C    C
3   GE    A    A
4   XA    B    B
5   CA    C    C
6   YA    C    C
7   FR    B    B
8   XA    C    C

注意:Code 中的字符串被缩短为两个字符,但在我的数据集中更长,所以我希望使用 startswith

问题类似于start/stop信号,我之前回答过,但是没找到。所以这是解决方案以及您提到的其他内容:

# check for C
is_C = df.Val1.eq('C') & df.Val2.eq('C')

# check for start substring with regex
startswith = df.Code.str.match("^(FR|GE|GA)")

# merge the two series
# startswith is 0, is_C is 1
mask = np.select((startswith,is_C), (0,1), np.nan)

# update mask with ffill 
# rows after an `is_C` and before a `startswith` will be marked with 1
mask = pd.Series(mask, df.index).ffill().fillna(0).astype(bool);

# update the dataframe
df.loc[mask, ['Val1','Val2']] = 'C'

输出

  Code Val1 Val2
0   CA    A    A
1   GA    B    B
2   YA    C    C
3   GE    A    A
4   XA    B    B
5   CA    C    C
6   YA    C    C
7   FR    B    B
8   XA    C    C