4

我在 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

我想将我的 DataFrame 子集为所有年份的2 月 2 日和 3 月 3 日之间的记录。

似乎应该有一种非常熊猫式的方式来做到这一点,但我正在努力寻找它。有什么帮助吗?

4

2 回答 2

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)
于 2013-09-11T17:19:59.937 回答
3

要选择涵盖多个月的年度返回期间的所有记录,请执行以下操作:

rng = pd.date_range('2010-1-1', periods=1000, freq='D')
df = pd.DataFrame(np.random.randn(len(rng)), index=rng, columns=['A'])

startMM, startdd = (2,15) # Feb 15th 
endMM, enddd = (10,3) # Oct 3rd

month_day = pd.concat([
                df.index.to_series().dt.month, 
                df.index.to_series().dt.day
            ], axis=1).apply(tuple, axis=1)

df[(month_day >= (startMM, startdd)) & (month_day <= (endMM, enddd))]

正如@IanS 在https://stackoverflow.com/a/45996897/2459096中提到的

于 2017-09-01T09:48:42.590 回答