在多索引Pandas数据帧的两个级别上对日期进行重采样

2024-06-14 00:06:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据帧和一个2级多索引。两个层次的多重指数都是相同的日期范围,每天间隔。我想每周对多重索引的两个级别的数据帧重新取样,但我遇到了麻烦。请看下面。在

为了举例说明,让我们将每个指数追溯到2周前:

d0 = date.today() - timedelta(days=14)
dates = pd.date_range(d0, date.today())
date_index = pd.MultiIndex.from_product([dates, dates], names=['cohort_date', 'event_date'])
df = pd.DataFrame(np.random.randint(0, 100, 225), index=date_index)

如果我直接重采样df,我会得到以下类型错误:

^{pr2}$

公平地说,我在第一个层次上拆开并重新取样,这给了我一半的答案:

df2 = df.unstack().resample('W', how='sum').T
print df2

cohort_date   2014-07-20  2014-07-27  2014-08-03
  event_date                                    
0 2014-07-16         177         424         115
  2014-07-17         408         392         197
  2014-07-18         174         435         222
  2014-07-19         180         392         141
  2014-07-20         304         252         155
  2014-07-21         242         236         228
  2014-07-22         139         159          77
  2014-07-23         117         293          68
  2014-07-24         308         353         246
  2014-07-25         254         471         160
  2014-07-26         258         240         144
  2014-07-27         297         360         148
  2014-07-28         284         303         202
  2014-07-29         218         399         144
  2014-07-30         227         286         160

现在,如果我尝试对第二个轴重新采样(理论上也是按日期索引),我会得到相同的错误:

df2.unstack().resample('W', how='sum')
[...]
TypeError: Only valid with DatetimeIndex or PeriodIndex

我现在有点不知所措,我会很感激每一个维度每周重新取样的任何帮助。在


Tags: 数据eventdftodaydateindex错误指数
1条回答
网友
1楼 · 发布于 2024-06-14 00:06:37

这需要0.14.1(它可能也适用于0.14.0)

注意,我认为它们是一个小问题,因为这个应该通过指定级别来工作(而不是重置并将其用作列)。在

文档是here

In [22]: df.reset_index().groupby([pd.Grouper(key='cohort_date',freq='W'),pd.Grouper(key='event_date',freq='W')]).sum()
Out[22]: 
                           0
cohort_date event_date      
2014-07-20  2014-07-20  1292
            2014-07-27  1665
            2014-08-03   764
2014-07-27  2014-07-20  1521
            2014-07-27  2317
            2014-08-03  1071
2014-08-03  2014-07-20   871
            2014-07-27  1006
            2014-08-03   306

相关问题 更多 >