Pandas resample and ffill 在最后留下 NaN
Pandas resample and ffill leaves NaN at the end
我想通过前向填充结果对系列进行从每周频率到每日频率的上采样。
如果我的原始系列的最后一个观察值是 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。
有人对这种行为有解释吗?
resample 和 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
。
resample()
returns DatetimeIndexResampler
你需要return原来的pandasSeries
.
可以使用asfreq()
的方法来完成,在填写Nan
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.asfreq.html.
之前
所以,这应该有效:
ts.resample('B').asfreq().ffill()
我想通过前向填充结果对系列进行从每周频率到每日频率的上采样。
如果我的原始系列的最后一个观察值是 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。
有人对这种行为有解释吗?
resample 和 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
。
resample()
returns DatetimeIndexResampler
你需要return原来的pandasSeries
.
可以使用asfreq()
的方法来完成,在填写Nan
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.asfreq.html.
所以,这应该有效:
ts.resample('B').asfreq().ffill()