我想通过向前填充结果来对每周到每天的频率进行升采样。
如果对我的原始系列的最后一次观察是NaN
,我希望该值将被以前的有效值代替,但仍保留为NaN
。
设定
import numpy as np
import pandas as pd
all_dates = pd.date_range(start='2018-01-01', freq='W-WED', periods=4)
ts = pd.Series([1, 2, 3], index=all_dates[:3])
ts[all_dates[3]] = np.nan
ts
Out[16]:
2018-01-03 1.0
2018-01-10 2.0
2018-01-17 3.0
2018-01-24 NaN
Freq: W-WED, dtype: float64
结果
ts.resample('B').ffill()
ts.resample('B').ffill()
Out[17]:
2018-01-03 1.0
2018-01-04 1.0
2018-01-05 1.0
2018-01-08 1.0
2018-01-09 1.0
2018-01-10 2.0
2018-01-11 2.0
2018-01-12 2.0
2018-01-15 2.0
2018-01-16 2.0
2018-01-17 3.0
2018-01-18 3.0
2018-01-19 3.0
2018-01-22 3.0
2018-01-23 3.0
2018-01-24 NaN
Freq: B, dtype: float64
当我期望最后一个值也是3时。
有人对此行为有解释吗?
重采样的目的ffill
是简单地从一周的第一天向前传播-如果一周的第一天是NaN
,则可以向前填充。例如:
ts.iloc[1] = np.nan
ts.resample('B').ffill()
2018-01-03 1.0
2018-01-04 1.0
2018-01-05 1.0
2018-01-08 1.0
2018-01-09 1.0
2018-01-10 NaN
2018-01-11 NaN
2018-01-12 NaN
2018-01-15 NaN
2018-01-16 NaN
2018-01-17 3.0
2018-01-18 3.0
2018-01-19 3.0
2018-01-22 3.0
2018-01-23 3.0
2018-01-24 NaN
Freq: B, dtype: float64
在大多数情况下,从上周的数据进行传播是不希望的。如果您想在原始(每周)系列中的值缺失的情况下使用前几周的数据,只需fillna
先使用即可ffill
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句