慕的地8271018
mask = (df['B'] == 'X').astype(int)mask = mask - mask.shift(-1)df.loc[mask == 1, 'C'] = 'str'dfOut[44]: A B C0 1 X 11 1 X 12 1 X str3 1 D 14 1 A 15 1 A 16 1 X str7 1 D 1解释:df = pd.DataFrame({ 'A' : [1,1,1,1,1,1,1,1], 'B' : ['X','X','X','D','A','A','X','D'], 'C' : [1,1,1,1,1,1,1,1], })dfOut[35]: A B C0 1 X 11 1 X 12 1 X 13 1 D 14 1 A 15 1 A 16 1 X 17 1 D 1现在你可以有一个面具,其中df['B']=='X':df['mask'] = (df['B'] == 'X').astype(int)dfOut[37]: A B C mask0 1 X 1 11 1 X 1 12 1 X 1 13 1 D 1 04 1 A 1 05 1 A 1 06 1 X 1 17 1 D 1 0为了找到要替换的行,您可以执行以下操作:df['mask'] = df['mask'] - df['mask'].shift(-1)dfOut[39]: A B C mask0 1 X 1 0.01 1 X 1 0.02 1 X 1 1.03 1 D 1 0.04 1 A 1 0.05 1 A 1 -1.06 1 X 1 1.07 1 D 1 NaN最后:df.loc[df['mask'] == 1, 'C'] = 'str' dfOut[41]: A B C mask0 1 X 1 0.01 1 X 1 0.02 1 X str 1.03 1 D 1 0.04 1 A 1 0.05 1 A 1 -1.06 1 X str 1.07 1 D 1 NaN