【问题标题】:Selecting Pandas DataFrame records for many years based on month & day range根据月份和日期范围选择多年的 Pandas DataFrame 记录
【发布时间】:2013-09-11 16:34:08
【问题描述】:

我在 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 日之间所有年份的记录。

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

【问题讨论】:

  • times之间有indexer_between_time,但我不认为日期有类似的便利功能。

标签: python pandas time-series


【解决方案1】:

我认为没有本地方法可以做到这一点 (there is with between times)。

但是你可以天真地做(这会很有效,但写起来很痛苦!):

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)

【讨论】:

  • 如果感兴趣的期限超过两个月,这不起作用
【解决方案2】:

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

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 中提到的那样

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    相关资源
    最近更新 更多