慕容森
df = pd.DataFrame({'A': {0: 1, 1: 10, 2: 20, 3: 30, 4: 40, 5: 50}, 'B': {0: 20, 1: 15, 2: 12, 3: 18, 4: 32, 5: 12}, 'C': {0: 3, 1: 11, 2: 25, 3: 32, 4: 17, 5: 4}})为您的条件创建一个布尔系列并识别连续的 True 或 False 组b_gt_c = df.B > df.Cgroups = b_gt_c.ne(b_gt_c.shift()).cumsum()In [107]: b_gt_cOut[107]: 0 True1 True2 False3 False4 True5 Truedtype: boolIn [108]: groupsOut[108]: 0 11 12 23 24 35 3dtype: int32按这些组分组;将每组的总和乘以条件;将结果分配给新的 df 列。gb = df.groupby(groups)for k,g in gb: df.loc[g.index,'D'] = g['A'].cumsum() * b_gt_c[g.index]In [109]: dfOut[109]: A B C D0 1 20 3 1.01 10 15 11 11.02 20 12 25 0.03 30 18 32 0.04 40 32 17 40.05 50 12 4 90.0您也可以跳过 for 循环:df['G'] = np.where(df.B.gt(df.C), df.A, np.NaN)group = df.B.gt(df.C).ne(df.B.gt(df.C).shift()).cumsum()df['G'] = df.groupby(group).G.cumsum().fillna(0)