如何更改 pandas 日期范围内的时间戳之一?

How to change one of the Timestamp in pandas date range?

我想把整个三月改成四月

date = pd.date_range("2008-01-01", "2021-03-31", freq = "QS-MAR")     
date

我尝试使用 timedelta 来更改它们。

可以运行,但数据不变

for time in date:
    print(type(time))
    if time.month == 3:
        time += datetime.timedelta(31)
date

DatetimeIndex(['2008-03-01', '2008-06-01', '2008-09-01', '2008-12-01',
               '2009-03-01', '2009-06-01', '2009-09-01', '2009-12-01',
               '2010-03-01', '2010-06-01', '2010-09-01', '2010-12-01',
               '2011-03-01', '2011-06-01', '2011-09-01', '2011-12-01',
               '2012-03-01', '2012-06-01', '2012-09-01', '2012-12-01',
               '2013-03-01', '2013-06-01', '2013-09-01', '2013-12-01',
               '2014-03-01', '2014-06-01', '2014-09-01', '2014-12-01',
               '2015-03-01', '2015-06-01', '2015-09-01', '2015-12-01',
               '2016-03-01', '2016-06-01', '2016-09-01', '2016-12-01',
               '2017-03-01', '2017-06-01', '2017-09-01', '2017-12-01',
               '2018-03-01', '2018-06-01', '2018-09-01', '2018-12-01',
               '2019-03-01', '2019-06-01', '2019-09-01', '2019-12-01',
               '2020-03-01', '2020-06-01', '2020-09-01', '2020-12-01',
               '2021-03-01'],
              dtype='datetime64[ns]', freq='QS-MAR')

是否可以实现?谢谢

你可以使用 pd.DateOffset

df['date'] = [i + pd.DateOffset(months=1) if i.month == 3 else i for i in df['date']]

改用pd.Series,这样您就可以直接赋值:

s = pd.Series(pd.date_range("2008-01-01", "2021-03-31", freq = "QS-MAR"))

s.loc[s.dt.month==3] += pd.offsets.DateOffset(months=1)

print (s)

0    2008-04-01
1    2008-06-01
2    2008-09-01
3    2008-12-01
4    2009-04-01
5    2009-06-01
...
48   2020-04-01
49   2020-06-01
50   2020-09-01
51   2020-12-01
52   2021-04-01
dtype: datetime64[ns]