2

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

4

1 回答 1

2

使用Series.asof是一种自然的方式,但我看到了一些缺点:

  • 您正在寻找一个接近的时间戳,其中asof搜索最新的时间戳。在您的示例中,如果您搜索datetime(2012, 11, 1)(早于 中的任何条目df),您将获得一个NaNvalue
  • 它仅适用于时间序列,因此您必须应用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))
于 2013-03-24T13:16:04.943 回答