使用Python中特定列的先前值填充NaN

时间:2017-10-17 04:05:24

标签: python pandas dataframe

我有一个Pandas数据框如下:

df =

                      open       high        low      close
Timestamp                                                      
2014-01-07 13:18:00  874.67040  892.06753  874.67040  892.06753
2014-01-07 13:19:00        NaN        NaN        NaN        NaN
2014-01-07 13:20:00        NaN        NaN        NaN        NaN
2014-01-07 13:21:00  883.23085  883.23085  874.48165  874.48165
2014-01-07 13:22:00        NaN        NaN        NaN        NaN

对于每个NaN,它们应该取前一段时间的值。

编辑:我尝试过使用df.fillna(method =' ffill')但它会让每个NaN直接取值在它上面。我希望每个NaN在它之前只接受Close的值。

使用ffill产量:

                      open       high        low      close
Timestamp                                                      
2014-01-07 13:18:00  874.67040  892.06753  874.67040  892.06753
2014-01-07 13:19:00  874.67040  892.06753  874.67040  892.06753

但我正在寻找:

                      open       high        low      close
Timestamp                                                      
2014-01-07 13:18:00  874.67040  892.06753  874.67040  892.06753
2014-01-07 13:19:00  892.06753  892.06753  892.06753  892.06753

2 个答案:

答案 0 :(得分:4)

几种方式:

.listjawaban
In [3166]: df.apply(lambda x: x.fillna(df.close.shift())).ffill()
Out[3166]:
                          open       high        low      close
Timestamp
2014-01-07 13:18:00  874.67040  892.06753  874.67040  892.06753
2014-01-07 13:19:00  892.06753  892.06753  892.06753  892.06753
2014-01-07 13:20:00  892.06753  892.06753  892.06753  892.06753
2014-01-07 13:21:00  883.23085  883.23085  874.48165  874.48165
2014-01-07 13:22:00  874.48165  874.48165  874.48165  874.48165

答案 1 :(得分:0)

您可以填充关闭,然后回填轴1上的其余部分:

df.close.fillna(method='ffill', inplace=True)
df.fillna(method='backfill', axis=1, inpace=True)