I have a DataFrame that has a MultiIndex index. It can be regenerated as follows:
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)
OUTPUT:
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:
dates_of_interest = [datetime(2012,11,1), datetime(2012,11,6)]
I am interested in creating a dataframe with a subset of the following criteria:
- date is nearest to one of the dates of interest
- label has 'A' in the string
So the result of my subindex would look like the following:
observation1 observation2
date label
2012-11-02 A12 79.373668 224
2012-11-07 A12 84.807516 396
Ideally, I would be able to get data for all observations "near" the criteria, so that the return dataset might look like:
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
But for a start I would just be happy to get the first result. I suspect that I need to use searchsort and asof, but I am not quite sure how to do that with. A MultiIndex.
Does anyone know how to get there from here?
Regards