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

2024-06-23 19:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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,他们应该取上一个时期的收盘价。在

编辑:我试过用费尔纳(method='ffill')但它使每个NaN取其正上方的值。我只想把每一个值都取出来。在

使用ffill产量:

^{pr2}$

但我在寻找:

                      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

Tags: 数据编辑pandasdfcloseopennanmethod
2条回答

几种方法:

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

^{pr2}$

关闭其余部分并填充轴1:

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

相关问题 更多 >

    热门问题