【问题标题】:How to select only the last n days every month in the given pd.DatetimeIndex如何在给定的 pd.DatetimeIndex 中仅选择每个月的最后 n 天
【发布时间】:2022-01-25 22:52:22
【问题描述】:

例如,

datetimeidx = pd.DatetimeIndex(
          ['1999-03-01', '1999-03-02', '1999-03-03', '1999-03-04',
           '1999-03-05', '1999-03-08', '1999-03-09', '1999-03-10',
           '1999-03-11', '1999-03-12', '2021-11-16', '2021-11-17', 
           '2021-11-18', '2021-11-19', '2021-11-22', '2021-11-23', 
           '2021-11-24', '2021-11-26', '2021-11-29', '2021-11-30'])

如果n=3,我想要的是:

datetimeidx = pd.DatetimeIndex(
          ['1999-03-10','1999-03-11', '1999-03-12', 
           '2021-11-26', '2021-11-29', '2021-11-30'])

关键是我只想从'给定'pd.DatetimeIndex中选择

【问题讨论】:

    标签: python pandas dataframe datetimeindex


    【解决方案1】:

    您可以按年和月分组,然后使用pandas.Series.tail

    n = 3
    
    pd.DatetimeIndex(datetimeidx
                      .to_series()
                      .groupby([datetimeidx.year, datetimeidx.month])
                      .tail(n))
    
    DatetimeIndex(['1999-03-10', '1999-03-11', '1999-03-12', '2021-11-26',
                   '2021-11-29', '2021-11-30'],
                  dtype='datetime64[ns]', freq=None)
    

    【讨论】:

      【解决方案2】:

      你可以使用:

      g = pd.Series(datetimeidx.year).astype(str) + '-' + pd.Series(datetimeidx.month).astype(str)
      print(pd.DatetimeIndex(pd.Series(datetimeidx).sort_values().groupby(g).tail(3)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-20
        • 1970-01-01
        • 1970-01-01
        • 2017-05-03
        • 1970-01-01
        • 2018-09-21
        • 1970-01-01
        相关资源
        最近更新 更多