【问题标题】:How to select specific quarter in Pandas timeseries如何在 Pandas 时间序列中选择特定季度
【发布时间】:2016-08-24 14:46:02
【问题描述】:

从时间序列中选择特定行的最佳方法是什么?

我有一些数据:

indexed = df.set_index("Month").resample("Q-MAR", how="sum")['count']
indexed

Month
2010-12-31     6942
2011-03-31    23677
2011-06-30    24131
2011-09-30    23144
2011-12-31    22249
2012-03-31    24216
2012-06-30    22938
2012-09-30    25468
2012-12-31    21733
2013-03-31    21385
2013-06-30    23093
2013-09-30    26206
2013-12-31    22248
2014-03-31    20737
2014-06-30    23384
2014-09-30    25285
2014-12-31    22210
2015-03-31    22627
2015-06-30    25185
2015-09-30    27038
2015-12-31    25352
2016-03-31    16694
Freq: Q-MAR, Name: count, dtype: int64

我可以切出单个条目,如下所示:

indexed.ix["2012-09-30"]
25468

indexed.ix["2015-09-30"]
27038

但是如何选择两者?

我试过了:

indexed.ix[["2012-09-30", "2015-09-30"],:]

返回太多索引器错误...

虽然

indexed.ix[["2012-09-30", "2015-09-30"]]

回来

Month
2012-09-30   NaN
2015-09-30   NaN

我不明白为什么

indexed.ix["2012-09-30", "2015-09-30"]

返回

25468

谁能给我解释一下好吗?

【问题讨论】:

    标签: python pandas indexing time-series


    【解决方案1】:

    如果您指定正确的 dtypes,则按索引访问会按预期工作:

    In [13]: df.loc[[pd.to_datetime('2012-09-30'),pd.to_datetime('2015-09-30')]]
    Out[13]:
                Count
    Month
    2012-09-30  25468
    2015-09-30  27038
    
    In [14]: df.loc[['2012-09-30','2015-09-30']]
    Out[14]:
                Count
    Month
    2012-09-30    NaN
    2015-09-30    NaN
    

    更新:

    从 Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers 开始。

    【讨论】:

      【解决方案2】:

      我发现这个答案对索引很有用: pandas, python - how to select specific times in timeseries

      indexed[(pd.Index(indexed.index.quarter).isin([3])) & (pd.Index(indexed.index.year).isin([2012,2015]))]
      
      Month
      2012-09-30    25468
      2015-09-30    27038
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-30
        • 2014-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        相关资源
        最近更新 更多