【问题标题】:How to filter specifc months from Pandas datetime index如何从 Pandas 日期时间索引中过滤特定月份
【发布时间】:2018-01-03 06:38:20
【问题描述】:

我有一个从 2000 年到 2010 年的每日数据集。我已经通过

设置了“GregDate”列
df.set_index(pd.DatetimeIndex(df['GregDate'])) 

作为索引。现在我只想调查从 11 月到 3 月的几个月(所有十年)。

我的数据框如下所示:

                Sigma        Lat        Lon
GregDate                                   
2000-01-01  -5.874062  79.913437 -74.583125
2000-01-02  -6.794000  79.904000 -74.604000
2000-01-03  -5.826061  79.923939 -74.548485
2000-01-04  -5.702439  79.916829 -74.641707
...
2009-07-11 -10.727381  79.925952 -74.660714
2009-07-12 -10.648000  79.923667 -74.557333
2009-07-13 -11.123095  79.908810 -74.596190

[3482 rows x 3 columns]

我已经看过这个question,但我仍然无法解决我的问题。

【问题讨论】:

    标签: python python-3.x pandas datetime


    【解决方案1】:

    我认为你需要boolean indexingDatetimeIndex.monthIndex.isin

    df = df[df.index.month.isin([11,12,1,2,3])]
    print (df)
                   Sigma        Lat        Lon
    GregDate                                  
    2000-01-01 -5.874062  79.913437 -74.583125
    2000-01-02 -6.794000  79.904000 -74.604000
    2000-01-03 -5.826061  79.923939 -74.548485
    2000-01-04 -5.702439  79.916829 -74.641707
    

    【讨论】:

    • 我使用的是 Pandas 版本 0.19.2,这给了我一个错误,即“AttributeError: 'numpy.ndarray' object has no attribute 'isin'”。 df.index.month 是一个 numpy 数组;在此解决方案起作用之前,我必须转换为熊猫系列。这只是版本更改吗?
    • 能够使用alldat['month']=alldat.index.month alldat[alldat.month.isin([11,12,1,2,3])]进行过滤
    • @EHB 如果使用旧的 pandas 尝试 numpy df = df[np.in1d(df.index.month, [11,12,1,2,3])] print (df),未经测试。
    【解决方案2】:
    In [10]: df.query("index.dt.month in [11,12,1,2,3]")
    Out[10]:
                   Sigma        Lat        Lon
    GregDate
    2000-01-01 -5.874062  79.913437 -74.583125
    2000-01-02 -6.794000  79.904000 -74.604000
    2000-01-03 -5.826061  79.923939 -74.548485
    2000-01-04 -5.702439  79.916829 -74.641707
    

    【讨论】:

      猜你喜欢
      • 2018-01-24
      • 2018-08-06
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2018-02-25
      • 1970-01-01
      相关资源
      最近更新 更多