[英]Resampling over dates in both levels of a MultiIndex Pandas DataFrame
我有一個帶有2級MultiIndex的pandas DataFrame。 MultiIndex的兩個級別都是相同的日期范圍,每天間隔。 我想每周對MultiIndex的兩個級別的DataFrame進行重新采樣,但是遇到了麻煩。 請看下面。
為了舉例說明,讓我們將每個索引追溯到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重新采樣,則會收到以下TypeError:
df.resample('W', how='sum')
[...]
TypeError: Only valid with DatetimeIndex or PeriodIndex
公平地說,我在第一層拆箱並重新采樣,這給出了一半的答案:
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
我現在不知所措,感謝您對每周在每個維度上進行重新采樣所提供的幫助。
這需要0.14.1(也可以在0.14.0中使用)
注意,我認為它們是一個小問題,因為這應該通過指定級別(而不是將其重置並用作列)來起作用。
文件在這里
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.