如何增加Date类型的索引

时间:2017-07-22 11:19:58

标签: python pandas numpy

我正在尝试将索引增加1以用于以下数组:

Date          High
2017-02-01    253.20 
2017-02-02    252.42
2017-02-03    252.18
2017-02-06    257.82
2017-02-07    260.00

我知道我们可以使用timedelta(days=1)来增加日期,但这会生成我的数组可能没有的日期。 那么有没有办法增加索引?

并且在递增之后,我如何获得该递增索引的值?

1 个答案:

答案 0 :(得分:2)

使用to_timedelta

df.index = df.index + pd.to_timedelta(1, unit='D')
print (df)
              High
Date              
2017-02-02  253.20
2017-02-03  252.42
2017-02-04  252.18
2017-02-07  257.82
2017-02-08  260.00

或者可以使用shift

df = df.shift(1, freq='D')
print (df)
              High
Date              
2017-02-02  253.20
2017-02-03  252.42
2017-02-04  252.18
2017-02-07  257.82
2017-02-08  260.00

编辑:

对于替换DatetimeIndex,可以rename使用dict

d1 = pd.to_datetime('2017-02-03')
d2 = d1 + pd.to_timedelta(5, unit='D')
df = df.rename(index={d1:d2})
print (df)
              High
Date              
2017-02-01  253.20
2017-02-02  252.42
2017-02-08  252.18
2017-02-06  257.82
2017-02-07  260.00

对于选择3.索引值:

d1 = df.index[2]
d2 = d1 + pd.to_timedelta(5, unit='D')
df = df.rename(index={d1:d2})
print (df)
              High
Date              
2017-02-01  253.20
2017-02-02  252.42
2017-02-08  252.18
2017-02-06  257.82
2017-02-07  260.00