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

时间:2021-06-24 18:06:48

标签: python pandas dataframe apply

假设我有一个 Pandas DataFrame:

<头>
行数 页面名称 感兴趣
0 错误
1 照片 错误
2 列表 真的
3 照片 错误
4 照片 错误
5 照片 错误
6 错误
7 照片 错误
仅当带有 OfInterest 的所有行的

PageName=photo 值遵循 True 时,才应将其设置为 PageName=list

在我想要的输出中,行 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)

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

1 个答案:

答案 0 :(得分:3)

您可以在这里尝试替换和填充,然后只比较填充的值是否为'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