在Pandas中使用.asof和MultiIndex

时间:2016-10-07 16:34:08

标签: python pandas

我已经看过几次这个问题,但没有回答。简短版本:

我有一个带有两级DataFrame索引的panda MultiIndex;两个级别都是整数。如何在此.asof()上使用DataFrame

长版:

我有DataFrame个时间序列数据:

>>> df
                            A
2016-01-01 00:00:00  1.560878
2016-01-01 01:00:00 -1.029380
...                       ...
2016-01-30 20:00:00  0.429422
2016-01-30 21:00:00 -0.182349
2016-01-30 22:00:00 -0.939461
2016-01-30 23:00:00  0.009930
2016-01-31 00:00:00 -0.854283

[721 rows x 1 columns]

然后构建该数据的每周模型:

>>> df['weekday'] = df.index.weekday
>>> df['hour_of_day'] = df.index.hour
>>> weekly_model = df.groupby(['weekday', 'hour_of_day']).mean()
>>> weekly_model
                            A
weekday hour_of_day          
0       0            0.260597
        1            0.333094
...                       ...
        20           0.388932
        21          -0.082020
        22          -0.346888
        23           1.525928
[168 rows x 1 columns]

是什么给了我DataFrame上面描述的索引。

我现在正试图将该模型推断为年度时间序列:

>>> dates = pd.date_range('2015/1/1', '2015/12/31 23:59', freq='H')
>>> annual_series = weekly
weekly        weekly_model  
>>> annual_series = weekly_model.A.asof((dates.weekday, dates.hour))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/core/series.py", line 2657, in asof
    locs = self.index.asof_locs(where, notnull(values))
  File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/indexes/base.py", line 1553, in asof_locs
    locs = self.values[mask].searchsorted(where.values, side='right')
ValueError: operands could not be broadcast together with shapes (8760,) (2,) 
>>> dates = pd.date_range('2015/1/1', '2015/12/31 23:59', freq='H')
>>> annual_series = weekly_model.A.asof((dates.weekday, dates.hour))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/core/series.py", line 2657, in asof
    locs = self.index.asof_locs(where, notnull(values))
  File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/indexes/base.py", line 1553, in asof_locs
    locs = self.values[mask].searchsorted(where.values, side='right')
ValueError: operands could not be broadcast together with shapes (8760,) (2,) 

这个错误意味着什么,以及最好的方法是什么?

到目前为止,我提出的最好的是:

>>> annual_series = weekly_model.A.loc[list(zip(dates.weekday, dates.hour))]

它有效,但这意味着首先将zip迭代器转换为列表,这对内存不友好。有没有办法避免这种情况?

1 个答案:

答案 0 :(得分:1)

我多次阅读您的帖子,我想我终于得到了您想要实现的目标。

试试这个:

df['weekday'] = df.index.weekday
df['hour_of_day'] = df.index.hour
weekly_model = df.groupby(['weekday', 'hour_of_day']).mean()
dates = pd.date_range('2015/1/1', '2015/12/31 23:59', freq='H')

然后像这样使用合并:

annual_series = pd.merge(df.reset_index(), weekly_model.reset_index(), on=['weekday', 'hour_of_day']).set_index('date')

现在您可以使用asof,因为您将日期作为索引

annual_series.asof(dates)

是你在找什么?