获取 offset/rolling/shift 为 1 的两列之差

Get the difference of two columns with an offset/rolling/shift of 1

愚蠢的问题:我有两列 AB 并且想创建一个 new_col,这实际上是当前 B 和上一个 A。以前例如表示当前行之前的行。如何实现(甚至可能使用可变偏移)?

目标:

df
| A | B  | new_col  |
|---|----|----------|
| 1 | 2  | nan (or2)|
| 3 | 4  | 3        |
| 5 | 10 | 7        |

伪代码:

new_col[0] = B[0] - 0
new_col[1] = B[1] - A[0]
new_col[2] = B[2] - A[1]

使用Series.shift:

df['new_col'] = df['B'] - df['A'].shift()

   A   B  new_col
0  1   2      NaN
1  3   4      3.0
2  5  10      7.0