我有一个包含3列的日期框架,如下所示:
FirstEpisode ShowOnAir AfterPremier
0 0 0
0 0 0
1 1 1
0 1 2
0 1 3
0 0 0
1 1 1
0 1 2
这里的条件是,当第一集== 1& ShowOnAir == 1,然后AfterPremier应该变为1,并且,如果下次观察中ShowOnAir的值仍为1,那么AfterPremier的值应该增加1,直到ShowOnAir的值不再为0,
如果我可以获得相同的帮助,我将非常感激
答案 0 :(得分:1)
df.iterrows
的解决方案:
df['AfterPremier'] = 0
df_to_iter = df.copy()
for i, row in df_to_iter.iterrows():
if row['FirstEpisode'] == 1 and row['ShowOnAir'] == 1:
row['AfterPremier'] = 1
if row['ShowOnAir'] == 1 and row['FirstEpisode'] == 0 and df.loc[i-1, 'AfterPremier'] != 0:
row['AfterPremier'] = df.loc[i-1, 'AfterPremier'] + 1
In [121]: df
Out[121]:
FirstEpisode ShowOnAir AfterPremier
0 0 0 0
1 0 0 0
2 1 1 1
3 0 1 2
4 0 1 3
5 0 0 0
6 1 1 1
7 0 1 2