我正在重新取样Pandas TimeSeries。时间序列由二进制值(它是一个分类变量)组成,没有缺失值,但在重新采样之后会出现NaN。这怎么可能?
我无法在此处发布任何示例数据,因为它是敏感信息,但我按如下方式创建并重新采样系列:
series = pd.Series(data, ts)
series_rs = series.resample('60T', how='mean')
答案 0 :(得分:8)
upsampling
转换为常规时间间隔,因此如果没有样本,则会获得NaN
。
您可以按fill_method='bfill'
或向前 - fill_method='ffill'
或fill_method='pad'
向后填充缺失值。
import pandas as pd
ts = pd.date_range('1/1/2015', periods=10, freq='100T')
data = range(10)
series = pd.Series(data, ts)
print series
#2015-01-01 00:00:00 0
#2015-01-01 01:40:00 1
#2015-01-01 03:20:00 2
#2015-01-01 05:00:00 3
#2015-01-01 06:40:00 4
#2015-01-01 08:20:00 5
#2015-01-01 10:00:00 6
#2015-01-01 11:40:00 7
#2015-01-01 13:20:00 8
#2015-01-01 15:00:00 9
#Freq: 100T, dtype: int64
series_rs = series.resample('60T', how='mean')
print series_rs
#2015-01-01 00:00:00 0
#2015-01-01 01:00:00 1
#2015-01-01 02:00:00 NaN
#2015-01-01 03:00:00 2
#2015-01-01 04:00:00 NaN
#2015-01-01 05:00:00 3
#2015-01-01 06:00:00 4
#2015-01-01 07:00:00 NaN
#2015-01-01 08:00:00 5
#2015-01-01 09:00:00 NaN
#2015-01-01 10:00:00 6
#2015-01-01 11:00:00 7
#2015-01-01 12:00:00 NaN
#2015-01-01 13:00:00 8
#2015-01-01 14:00:00 NaN
#2015-01-01 15:00:00 9
#Freq: 60T, dtype: float64
series_rs = series.resample('60T', how='mean', fill_method='bfill')
print series_rs
#2015-01-01 00:00:00 0
#2015-01-01 01:00:00 1
#2015-01-01 02:00:00 2
#2015-01-01 03:00:00 2
#2015-01-01 04:00:00 3
#2015-01-01 05:00:00 3
#2015-01-01 06:00:00 4
#2015-01-01 07:00:00 5
#2015-01-01 08:00:00 5
#2015-01-01 09:00:00 6
#2015-01-01 10:00:00 6
#2015-01-01 11:00:00 7
#2015-01-01 12:00:00 8
#2015-01-01 13:00:00 8
#2015-01-01 14:00:00 9
#2015-01-01 15:00:00 9
#Freq: 60T, dtype: float64
答案 1 :(得分:1)
请注意,fill_method现已弃用。 resample()
现在返回一个重采样对象,您可以在其上执行操作,就像groupby对象一样。
常见的下采样操作:
.mean()
.sum()
.agg()
.apply()
上采样操作:
.ffill()
.bfill()
请参阅文档中的whats-new消息 https://pandas.pydata.org/pandas-docs/stable/whatsnew.html#whatsnew-0180-breaking-resample
所以示例将成为
series_rs = series.resample('60T').mean()