如何 select 在给定的 pd.DatetimeIndex 每个月的最后 n 天

How to select only the last n days every month in the given pd.DatetimeIndex

例如,

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'])

重点是我想select只从'given'pd.DatetimeIndex

您可以按年和月分组,然后使用 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)

您可以使用:

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)))