给定此数据帧
import pandas as pd
idx_str = [
'blue',
'blue',
'blue',
'blue',
'red',
'red',
'red',
'red',
]
idx_date = [
pd.Timestamp('2010-01-01'),
pd.Timestamp('2010-01-05'),
pd.Timestamp('2010-01-06'),
pd.Timestamp('2010-01-10'),
pd.Timestamp('2010-01-01'),
pd.Timestamp('2010-01-05'),
pd.Timestamp('2010-01-06'),
pd.Timestamp('2010-01-10'),
]
data = [1,2,3,4,5,6,7,8]
df = pd.DataFrame(
data=zip(idx_str, idx_date, data),
columns=['idx_str', 'idx_dates', 'data'],
)
df.set_index([idx_str, idx_date], drop=True, inplace=True)
print(df)
data
blue 2010-01-01 1
2010-01-05 2
2010-01-06 3
2010-01-10 4
red 2010-01-01 5
2010-01-05 6
2010-01-06 7
2010-01-10 8
我想查询介于datetimeIndex
级和限制为第一级red
colored颜色 的两个日期之间的行
所以我想要这个:
data
red 2010-01-02 5
2010-01-03 6
由于多索引,我不能使用我找到的解决方案,例如
df.query("'2010-01-02' <= index <= '2010-01-09'")
df.loc['2010-01-02':'2010-01-09']
May be it wasn't so clear the first time so I edited the end result I wanted个