在 pandas 中更改此行和上一行矢量化

Change this row and previous row vectorised in pandas

我有一个数据帧,它对行 'this' 中的最后一个值进行编码 'last'。我想根据列表中的值匹配 table 中的 'this' 列,例如['b', 'c'] 然后将前一行的 'this' 以及这一行的 'last' 更改为此类匹配项中的值 'd'。

比如我想改成这样:

this last
a
b a
a b
c a
a c

进入这个:

this last
d
b d
d b
c d
a c

如果迭代的话这很简单,但是太慢了:

for i, v in df['this'].iteritems():
    if v in ['b', 'c']:
        df['this'].iloc[i - 1] = 'd'
        df['last'].iloc[i] = 'd'

我相信这可以通过将 df.this.shift(-1) 分配给列 'last' 来完成,但是当我匹配列表 ['b', 'c'] 中的值时,我不确定如何执行此操作.如何在不迭代的情况下执行此操作?

df
   this last
0   a   NaN
1   b   a
2   a   b
3   c   a
4   a   c

您可以使用 isin 获取值属于列表 (l1) 的布尔索引。然后用 d 填充相应的 last。然后 shift 向上方向的布尔索引,用 d

填充所需的 this
l1 = ['b', 'c']
this_in_l1 = df['this'].isin(l1)
df.loc[this_in_l1, 'last'] = 'd'
df.loc[this_in_l1.shift(-1, fill_value=False), 'this'] = 'd'

df
  this last
0   d   NaN
1   b   d
2   d   b
3   c   d
4   a   c