如何填充 python 时间序列中特定日期范围内的 nan 值?

How to fill nan values from a specific date range in a python time series?

我正在处理一个时间序列,该时间序列记录了从 2013 年到 2021 年巴西城市市场上鱼的价格,原始数据集包含三列,一列包含最便宜的价值,另一列包含最贵的,最后是其他的,它们的平均价格是他们收集数据当天的价格。我已经为相应的列创建了三个子集,日期并对日期进行了索引,然后进行了一些解释性分析,我发现 2013 年和 2014 年的某些特定月份具有 nan 值。

dfmin.loc['2013-4-1':'2013-7-31']
    min
date    
2013-04-01 12:00:00 16.0
2013-04-02 12:00:00 16.0
2013-05-22 12:00:00 NaN
2013-05-23 12:00:00 NaN
2013-05-24 12:00:00 NaN
2013-05-27 12:00:00 NaN
2013-05-28 12:00:00 NaN
2013-05-29 12:00:00 NaN
2013-05-30 12:00:00 NaN
2013-05-31 12:00:00 NaN
2013-06-03 12:00:00 NaN
2013-06-04 12:00:00 NaN
2013-06-05 12:00:00 NaN
2013-06-06 12:00:00 NaN
2013-06-07 12:00:00 NaN
2013-06-10 12:00:00 NaN
2013-06-11 12:00:00 NaN
2013-06-12 12:00:00 NaN
2013-06-13 12:00:00 NaN
2013-06-14 12:00:00 NaN
2013-06-17 12:00:00 NaN
2013-06-18 12:00:00 NaN
2013-06-19 12:00:00 15.8
2013-06-20 12:00:00 15.8
2013-06-21 12:00:00 15.8
​```

I want to fill these NaN values from the month 05 with the average value from the medium price from the month 04 and the month 06, how can I make it?

IIUC,可以使用简单的索引:

# if needed, convert to datetime
#df.index = pd.to_datetime(df.index)

df.loc[df.index.month==5, 'min'] = df.loc[df.index.month.isin([4,6]), 'min'].mean()

或者如果您第 5 个月没有 NaN:

mask = df.index.month==5
df.loc[mask, 'min'] = (df.loc[mask, 'min']
                         .fillna(df.loc[df.index.month.isin([4,6]), 'min'].mean())
                       )

输出:

                       min
date                      
2013-04-01 12:00:00  16.00
2013-04-02 12:00:00  16.00
2013-05-22 12:00:00  15.88
2013-05-23 12:00:00  15.88
2013-05-24 12:00:00  15.88
2013-05-27 12:00:00  15.88
2013-05-28 12:00:00  15.88
2013-05-29 12:00:00  15.88
2013-05-30 12:00:00  15.88
2013-05-31 12:00:00  15.88
2013-06-03 12:00:00    NaN
2013-06-04 12:00:00    NaN
2013-06-05 12:00:00    NaN
2013-06-06 12:00:00    NaN
2013-06-07 12:00:00    NaN
2013-06-10 12:00:00    NaN
2013-06-11 12:00:00    NaN
2013-06-12 12:00:00    NaN
2013-06-13 12:00:00    NaN
2013-06-14 12:00:00    NaN
2013-06-17 12:00:00    NaN
2013-06-18 12:00:00    NaN
2013-06-19 12:00:00  15.80
2013-06-20 12:00:00  15.80
2013-06-21 12:00:00  15.80