根据月和日范围选择Pandas DataFrame记录多年

JD *_*ong 3 python time-series pandas

我在Pandas DataFrame中有一些日常数据,它有一个很好的索引.像这样的东西:

import pandas as pd
import numpy as np

rng = pd.date_range('1/1/2010', periods=1000, freq='D')
ts = pd.DataFrame(randn(len(rng)), index=rng, columns=['vals'])
print ts.head()

                vals
2010-01-01  1.098302
2010-01-02 -1.384821
2010-01-03 -0.426329
2010-01-04 -0.587967
2010-01-05 -0.853374
Run Code Online (Sandbox Code Playgroud)

我想将我的DataFrame子集化为仅存在于2月2日和3月3日之间的所有年份的记录.

似乎应该有一种非常像熊猫式的方式来做这件事,但我很难找到它.有帮助吗?

And*_*den 6

我不认为有一种本地方式可以做到这一点(有时间).

但你可以天真地做到这一点(这将是有效的,但写起来很痛苦!):

In [11]: ts[((ts.index.month == 2) & (2 <= ts.index.day)  # in Feb after the 2nd inclusive
              | (ts.index.month == 3) & (ts.index.day <= 3))]  # in March before the 3rd inclusive
Out[11]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 94 entries, 2010-02-01 00:00:00 to 2012-03-03 00:00:00
Data columns (total 1 columns):
vals    94  non-null values
dtypes: float64(1)
Run Code Online (Sandbox Code Playgroud)