选择年份范围内的特定月份 pandas

Selecting particular months over a range of years pandas

我导入了一个时间序列,我将其重新采样为每月时间步长,但是我想 select 所有年份只有三月、四月和五月(第 3、4 和 5 个月) .

不幸的是,这不是完全可重现的数据,因为它是一个特定的文本文件,但是有没有办法只隔离这个时间序列的所有第 3、4 和 5 个月?

# loading textfile

mjo = np.loadtxt('.../omi.1x.txt')

# setting up dates
dates = pd.date_range('1979-01', periods=mjo.shape[0], freq='D')

#resampling one of the columns to monthly data
MJO_amp = Series(mjo[:,6], index=dates) 

MJO_amp_month = MJO_amp.resample("M").mean()[:-27] #match to precipitation time series (ends feb 2019)

MJO_amp_month_normed = (MJO_amp_month - MJO_amp_month.mean())/MJO_amp_month.std()

MJO_amp_month_normed

1979-01-31    0.032398
1979-02-28   -0.718921
1979-03-31    0.999467
1979-04-30   -0.790618
1979-05-31    1.113730
                ...   
2018-10-31    0.198834
2018-11-30    0.221942
2018-12-31    1.804934
2019-01-31    1.359485
2019-02-28    1.076308
Freq: M, Length: 482, dtype: float64


print(MJO_amp_month_normed['2018-10'])

2018-10-31    0.198834
Freq: M, dtype: float64

我的思路是这样的:

def is_amj(month):
    return (month >= 4) & (month <= 6)

seasonal_data = MJO_amp_month_normed.sel(time=is_amj(MJO_amp_month_normed))

但我认为我的问题是文本文件不完全是 pandas 格式并且没有列标题...

您可以像这样将 pd.DatetimeIndexmonth 属性与 isin 一起使用:

df[df.index.month.isin([3,4,5])]