我有一个具有MultiIndex索引的DataFrame。它可以重新生成如下:
import pandas as pd
import numpy as np
from numpy.random import randn as randn
from numpy.random import randint as randint
from datetime import datetime
# setup data
obs1 = [ob if ob > 0 else ob *-1 for ob in randn(10)*100]
obs2 = [randint(1000) for i in range(10)]
labels = ['A12', 'B12', 'A12', 'A12', 'A12','B12', 'A12','B12', 'A13', 'B13']
dates = [datetime(2012, 11, i) for i in range(1,11)]
dates[0] = dates[1]
dates[5] = dates[6]
# setup index and dataframe
m_idx = pd.MultiIndex.from_tuples(zip(dates, labels), names=['date', 'label'])
data_dict = {'observation1':obs1, 'observation2':obs2}
df = pd.DataFrame(data_dict, index=m_idx)
输出:
In [17]: df
Out[17]:
observation1 observation2
date label
2012-11-02 A12 79.373668 224
B12 130.841316 477
2012-11-03 A12 45.312814 835
2012-11-04 A12 163.776946 623
2012-11-05 A12 115.449437 722
2012-11-07 B12 38.537737 842
A12 84.807516 396
2012-11-08 B12 35.186265 707
2012-11-09 A13 60.171620 336
2012-11-10 B13 123.750614 540
感兴趣的日期:
dates_of_interest = [datetime(2012,11,1), datetime(2012,11,6)]
我有兴趣使用以下条件的子集创建数据框:
因此我的子索引的结果如下所示:
observation1 observation2
date label
2012-11-02 A12 79.373668 224
2012-11-07 A12 84.807516 396
理想情况下,我可以获得所有观察数据“接近”标准,以便返回数据集看起来像:
observation1 observation2
date label
2012-11-02 A12 79.373668 224
2012-11-05 A12 115.449437 722
2012-11-07 A12 84.807516 396
但是首先我会很高兴得到第一个结果。我怀疑我需要使用searchsort和asof,但我不太确定如何使用它。一个MultiIndex。
有谁知道如何从这里到达那里?
此致
答案 0 :(得分:2)
使用Series.asof
是一种自然的方式,但我看到了一些缺点:
asof
搜索最新时间戳。
在您的示例中,如果您搜索datetime(2012, 11, 1)
(早于df
中的任何条目),您将获得NaN
值。reset_index
应用于DataFrame
然后选择一些任意列作为时间序列。换句话说,它会让你的代码变得有点尴尬和错综复杂。这是一个更强大的替代方案,可以解决您的第一个任务,即使用numpy.searchsorted
搜索时间戳索引以获得近似命中:
import numpy as np
# it is important that df is sorted by date
df.sort_index(inplace=True)
dates_ix = df.index.levels[0]
nearest_date = lambda date: dates_ix[np.searchsorted(dates_ix, date)]
approx_dates = map(nearest_date, dates_of_interest)
# select the desired entries in the index
df.select(lambda (date, label): (date in approx_dates and
label.find('A')!=-1))