<p>使用<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer">^{<cd1>}</a>by helper <code>Series</code>和<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer">^{<cd3>}</a>创建的移位掩码,然后将<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.add.html" rel="nofollow noreferrer">^{<cd4>}</a>与<code>1</code>相加,并将<code>5</code>与<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mul.html" rel="nofollow noreferrer">^{<cd7>}</a>相加,对于下一列,使用<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer">^{<cd8>}</a>:</p>
<pre><code>m = df['Y'].eq(1)
df['Z'] = df.groupby(m.shift().bfill().cumsum()).cumcount().add(1).mul(5)
df['P'] = np.where(m, df.X.mul(df.Z), 0)
print (df)
X Y Z P
0 29 5 5 0
1 28 4 10 0
2 32 3 15 0
3 29 3 20 0
4 26 1 25 650
5 38 5 5 0
6 25 2 10 0
7 33 3 15 0
8 25 3 20 0
9 25 5 25 0
10 40 1 30 1200
11 30 6 5 0
12 31 3 10 0
13 38 5 15 0
</code></pre>