【问题标题】:How to change the date for datetime index to begining of the month如何将日期时间索引的日期更改为月初
【发布时间】:2019-05-15 16:51:59
【问题描述】:

我有一个具有如下 DatetimeIndex 的数据框:

df.index
DatetimeIndex(['2013-07-27', '2013-08-03', '2013-08-10', '2013-08-17',
               '2013-08-24', '2013-08-31', '2013-09-07', '2013-09-14',
               '2013-09-21', '2013-09-28',
               ...
               '2018-11-03', '2018-11-10', '2018-11-17', '2018-11-24',
               '2018-12-01', '2018-12-08', '2018-12-15', '2018-12-22',
               '2018-12-29', '2019-01-05'],
              dtype='datetime64[ns]', name='wdate', length=285, freq=None)

我想将每个日期更改为月初,即2013-07-27 应更改为 2013-07-01 如何在 python 中使用 pandas 数据框?

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    使用 MonthBegin 的问题在于它将日期 1 转换为上个月的日期 1。检查索引中的最后日期。

    i = pd.DatetimeIndex(['2013-07-27', '2013-08-03', '2013-08-10', '2013-08-17',
           '2013-08-24', '2013-08-31', '2013-09-07', '2013-09-14',
           '2013-09-21', '2013-09-28',
           '2018-11-03', '2018-11-10', '2018-11-17', '2018-11-24',
           '2018-12-01', '2018-12-08', '2018-12-15', '2018-12-22',
           '2018-12-29', '2019-01-05', '2019-01-01'])
    
    i - pd.to_timedelta(df.index.day - 1, unit='d')
    
    DatetimeIndex(['2013-07-01', '2013-08-01', '2013-08-01', '2013-08-01',
                   '2013-08-01', '2013-08-01', '2013-09-01', '2013-09-01',
                   '2013-09-01', '2013-09-01', '2018-11-01', '2018-11-01',
                   '2018-11-01', '2018-11-01', '2018-12-01', '2018-12-01',
                   '2018-12-01', '2018-12-01', '2018-12-01', '2019-01-01',
                   '2019-01-01'],
                  dtype='datetime64[ns]', freq=None)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-24
      • 2017-08-27
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多