【问题标题】:Pandas DataFrame Resample: How to fill nan with previous "close" value?Pandas DataFrame Resample:如何用以前的“关闭”值填充 nan?
【发布时间】:2019-02-10 21:54:46
【问题描述】:

我正在从交易时间序列的数据框中创建重新采样的分钟数据,并获取“开盘”、“低”、“高”、“收盘”列,这很好。

dfOHLCV = pd.DataFrame()
dfOHLCV = df.price.resample('T').ohlc()

我的问题在于填写“nan”。当在给定的分钟间隔内没有交易时,该值变为“nan”。 Nans可以通过申请填写

.fillna(method='ffill') # which replaces nan by the value in the previous period

然而,nan cell 中的开盘价不应来自其上一周期的开盘价,而是来自其前一周期的收盘价。

例子:

index | open | high | low | close
00001 | 3200 | 3250 | 3190| 3240
00002 | nan  | nan  | nan | nan

.fillna 将填充

00002 | 3200 | 3250 | 3190| 3240

但我想这样填写:

00002 | 3240 | 3240 | 3240| 3240

换句话说,我想用上一期的收盘价填充nan单元格。这怎么可能?

【问题讨论】:

    标签: pandas dataframe nan


    【解决方案1】:

    检查fillnadict

    df=df.fillna(dict.fromkeys(df.columns.tolist(),df.close.ffill()))
    df
             open    high     low   close
    index                                
    1      3200.0  3250.0  3190.0  3240.0
    2      3240.0  3240.0  3240.0  3240.0
    

    【讨论】:

    • 太棒了!谢谢!
    猜你喜欢
    • 2015-02-14
    • 2022-01-07
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多