检查年份是否在 PeriodIndex 中

Check if a year is in PeriodIndex

我有一个由 PeriodIndex 索引的 DataFrame,需要检查索引是否包含年份。

这是我目前尝试过的片段:

In [1]: import pandas as pd

In [2]: period_ix = pd.period_range(start='2018-07-01', end='2019-04-30', freq='W')

In [3]: '2018' in period_ix
Out[3]: False

In [4]: '2018' in period_ix.year
Out[4]: False

In [5]: 2018 in period_ix.year
Out[5]: True

In [6]: 2018 in period_ix
Out[6]: False

In [7]: '2019' in period_ix
Out[7]: True

In [8]: '2019' in period_ix.year
Out[8]: False

In [9]: 2019 in period_ix.year
Out[9]: True

In [10]: 2019 in period_ix
Out[10]: False

我已经使用 int(year) in period_ix.year 因为它每年都会产生预期的结果(无论是字符串还是整数)。

不过,我对使用 '2018' in period_ix 很感兴趣,因为它看起来比我正在做的更新颖、更一致。我想如果有人输入 '2018',它会被解释为 '2018-01-01',因此此处为 False。

只是添加一点 if 信息,partial string indexingPeriodIndex 的执行方式不同。你可以最直接地看到这个:

period_ix.get_loc('2018')
#KeyError: Period('2018-01-01/2018-01-07', 'W-SUN')

相关行位于源代码here处,所以可以看到字符串'2018'被转换成了

pd.period('2018', freq=period_ix.freq)
#Period('2018-01-01/2018-01-07', 'W-SUN')

您的 PeriodIndex 中不存在。


您可以使用 PeriodIndex._get_string_slice

获得相同的部分字符串切片行为
period_ix[period_ix._get_string_slice('2018')]
#PeriodIndex(['2018-06-25/2018-07-01', '2018-07-02/2018-07-08',
#             '2018-07-09/2018-07-15', '2018-07-16/2018-07-22',
#             '2018-07-23/2018-07-29', '2018-07-30/2018-08-05',
#             '2018-08-06/2018-08-12', '2018-08-13/2018-08-19',
#             ....
#             '2018-12-24/2018-12-30', '2018-12-31/2019-01-06'],
#            dtype='period[W-SUN]', freq='W-SUN')

仅仅一年,我同意你的 int(year) in period_ix.year 版本是合适的。虽然如果你想要部分年份和月份,你可能需要这样的东西:

not period_ix[period_ix._get_string_slice('2018-08')].empty
True

def contains_partl(date, pidx):
    sl = pidx._get_string_slice(date)  #slice
    return sl.start != sl.stop

contains_partl('2018', period_ix)
#True

contains_partl('2018-05', period_ix)
#False