擅长:python、mysql、java
<p>我们可以访问<code>groupby object</code>中的groupid和groups,然后在每次迭代中生成<code>changed</code>列:</p>
<pre><code>groups = []
for _, grp in df.groupby('id_police'):
grp['changes'] = (grp[['prime', 'prime2']].shift().eq(0).any(axis=1) & grp[['prime', 'prime2']].ne(0).any(axis=1)).astype(int)
groups.append(grp)
df_final = pd.concat(groups).sort_index()
</code></pre>
<hr/>
<p>这就产生了</p>
<pre><code>print(df_final)
id_police date prime prime2 changes
0 p123 24/01/2017 0 0 0
1 p123 24/11/2017 0 30 1
2 p123 25/02/2018 10 10 1
3 b123 24/02/2018 20 20 0
4 b123 24/03/2018 30 0 0
</code></pre>
<hr/>
<p>如果要关闭<code>SetCopyWarning</code>,请使用以下命令:</p>
<pre><code>pd.options.mode.chained_assignment = None
</code></pre>