【发布时间】:2021-06-24 18:06:48
【问题描述】:
假设我有一个 pandas DataFrame:
| RowNum | PageName | OfInterest |
|---|---|---|
| 0 | home | False |
| 1 | photo | False |
| 2 | list | True |
| 3 | photo | False |
| 4 | photo | False |
| 5 | photo | False |
| 6 | home | False |
| 7 | photo | False |
只有当它们跟随PageName=list时,所有带有PageName=photo的行的OfInterest值才应设置为True。
在我想要的输出中,行 3,4,5 将被更改,而不是行 1, 7:
| RowNum | PageName | OfInterest |
|---|---|---|
| 0 | home | False |
| 1 | photo | False |
| 2 | list | True |
| 3 | photo | True |
| 4 | photo | True |
| 5 | photo | True |
| 6 | home | False |
| 7 | photo | False |
我尝试使用 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)
我知道我可以使用循环来完成同样的任务,但我想找到一个更优雅的解决方案。
【问题讨论】:
标签: python pandas dataframe apply