根据上一行的最新值更新行值

Update row value based on the most recent value of the previous row

假设我有一个 pandas DataFrame:

行数 页面名称 感兴趣
0
1 照片
2 列表 正确
3 照片
4 照片
5 照片
6
7 照片
只有在 PageName=list.

之后,具有 PageName=photo 的所有行的

OfInterest 值才应设置为 True

在我想要的输出中,行 3,4,5 将被更改,但行 1, 7:

不会更改
行数 页面名称 感兴趣
0
1 照片
2 列表 正确
3 照片 正确
4 照片 正确
5 照片 正确
6
7 照片

我尝试使用 apply() 执行此操作,但我似乎无法访问最近更改的值。

def changeInterest(x):
  followsOfInterest = (x['PageName'] == 'photo') and (x['PrevOfInterest'])
  return followsOfInterest or x['OfInterest']

df['PrevOfInterest'] = df['OfInterest'].shift(-1)
df['PrevOfInterest'] = df[['PageName', 'OfInterest', 'PrevOfInterest']].apply(changeInterest, axis=1)

我知道我可以使用循环来完成同样的事情,但我想找到一个更优雅的解决方案。

您可以在这里尝试替换和填充,然后比较填充值是否为 'list'

s = df['PageName'].replace('photo',np.nan).ffill().eq('list')|df['OfInterest']
df['OfInterest'] = s

print(df)

   RowNum PageName  OfInterest
0       0     home       False
1       1    photo       False
2       2     list        True
3       3    photo        True
4       4    photo        True
5       5    photo        True
6       6     home       False
7       7    photo       False