【问题标题】:Update row value based on the most recent value of the previous row根据上一行的最新值更新行值
【发布时间】: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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2019-07-06
      相关资源
      最近更新 更多