如何更改日期时间索引中的日期

时间:2019-06-01 20:58:19

标签: python-3.x pandas

考虑具有这样的索引的df:

index = pd.DatetimeIndex(['2018-04-26 15:55:00', '2018-04-26 16:00:00', '2018-04-26 16:05:00', '2018-04-26 16:10:00', '2018-04-26 16:15:00'], dtype='datetime64[ns]', name='date', freq=None)

df = pd.DataFrame({'x': [1,1,1,1,1]}, index = index)

In[308]: df
Out[308]: 
                     x
date                  
2018-04-26 15:55:00  1
2018-04-26 16:00:00  1
2018-04-26 16:05:00  1
2018-04-26 16:10:00  1
2018-04-26 16:15:00  1

如何在不使用shifttimedelta的情况下,将索引的日期部分设置为 任意 日期,同时保留时间部分完整的索引。例如,如何将日期从2018-04-26更改为2018-04-20并具有:

In[308]: df
Out[308]: 
                     x
date                  
2018-04-20 15:55:00  1
2018-04-20 16:00:00  1
2018-04-20 16:05:00  1
2018-04-20 16:10:00  1
2018-04-20 16:15:00  1

df.index.date = datetime.date(2018, 4, 20)指向AttributeError: can't set attribute

1 个答案:

答案 0 :(得分:1)

尝试使用日期时间的索引replace

df.index=df.index.map(lambda x : x.replace(day=20))
df
Out[785]: 
                     x
date                  
2018-04-20 15:55:00  1
2018-04-20 16:00:00  1
2018-04-20 16:05:00  1
2018-04-20 16:10:00  1
2018-04-20 16:15:00  1