使用另一个数据帧pandas的第一个值填充0和1系列的数据帧

时间:2016-05-18 18:24:16

标签: python python-2.7 pandas

我的df包含价格:

close
                  SPY         F      AAPL
Date                                     
1995-01-03  31.205567  5.503672  1.247298
1995-01-04  31.354707  5.651756  1.279801
1995-01-05  31.354707  5.602394  1.263550
1995-01-06  31.386606  5.602394  1.365121
1995-01-09  31.418575  5.701112  1.339220
1995-01-10  31.450542  5.602394  1.419970
1995-01-11  31.471809  5.602394  1.519510
1995-01-12  31.482511  5.553033  1.474819

我还有一组信号,其键和索引与“关闭”相同

signals
Out: 
                  SPY       F      AAPL
Date                                     
1995-01-03         0        0        0
1995-01-04         1        0        1
1995-01-05         1        1        1
1995-01-06         0        1        1
1995-01-09         0        0        0
1995-01-10         1        1        0
1995-01-11         1        1        0
1995-01-12         1        0        1

我想用连续的'1'系列填充数据帧'close'的第一个值,其中信号从0切换到1,如

df
Out: 
                  SPY           F         AAPL
Date                                     
1995-01-03         0            0          0
1995-01-04         31.354707    0          1.279801
1995-01-05         31.354707    5.602394   1.279801
1995-01-06         0            5.602394   1.279801
1995-01-09         0            0          0
1995-01-10         31.450542    5.602394   0
1995-01-11         31.450542    5.602394   0
1995-01-12         31.450542    0          1.474819

真的需要帮助。谢谢!

1 个答案:

答案 0 :(得分:6)

这是一种方法:

>>> starts = signals & (signals != signals.shift())
>>> (close.where(starts).ffill() * signals).fillna(0)
                  SPY         F      AAPL
Date                                     
1995-01-03   0.000000  0.000000  0.000000
1995-01-04  31.354707  0.000000  1.279801
1995-01-05  31.354707  5.602394  1.279801
1995-01-06   0.000000  5.602394  1.279801
1995-01-09   0.000000  0.000000  0.000000
1995-01-10  31.450542  5.602394  0.000000
1995-01-11  31.450542  5.602394  0.000000
1995-01-12  31.450542  0.000000  1.474819