【问题标题】:Get the difference of two columns with an offset/rolling/shift of 1获取偏移量/滚动/移位为 1 的两列的差异
【发布时间】:2020-04-12 03:08:14
【问题描述】:

愚蠢的问题:我有两列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]

【问题讨论】:

    标签: pandas dataframe series rolling-computation


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

    【讨论】:

    • 很明显.. 是的 - 我被数据框选项吸引了 rolling(..)
    猜你喜欢
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多