在等于值的位置填充列,直到另一个值-熊猫

时间:2020-03-05 03:55:36

标签: python pandas mask

我试图基于单独的列在ffill()的两个列中df个值。我希望继续填充直到满足条件。使用下面的df,其中Val1Val2等于C,我要填充后续行,直到Code中的字符串以{{1 }}。

['FR','GE','GA']

预期输出:

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

1 个答案:

答案 0 :(得分:1)

问题类似于我之前回答过的启动/停止信号,但是找不到。因此,这里是您提到的解决方案以及其他内容:

# 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