更改DateTimeIndex的日期

scl*_*cls 8 python pandas

我有一个名为csv文件data.csv,如

TS;val
10:00;0.1
10:05;0.2
10:10;0.3
10:15;0.4
Run Code Online (Sandbox Code Playgroud)

我使用这个脚本读了这个csv文件

#!/usr/bin/env python
import pandas as pd

if __name__ == "__main__":
    yyyy = 2013
    mm = 2
    dd = 1

    df = pd.read_csv('data.csv', sep=';', parse_dates=[0], index_col=0)

    print(df)
Run Code Online (Sandbox Code Playgroud)

我明白了

                     val
TS                      
2013-06-17 10:00:00  0.1
2013-06-17 10:05:00  0.2
2013-06-17 10:10:00  0.3
2013-06-17 10:15:00  0.4
Run Code Online (Sandbox Code Playgroud)

我想将每个DateTimeIndex的日期更改为2013-02-01

                     val
TS                      
2013-02-01 10:00:00  0.1
2013-02-01 10:05:00  0.2
2013-02-01 10:10:00  0.3
2013-02-01 10:15:00  0.4
Run Code Online (Sandbox Code Playgroud)

更简单的方法是什么?

And*_*den 11

时间戳有一个replace方法(就像日期时间一样):

In [11]: df.index.map(lambda t: t.replace(year=2013, month=2, day=1))
Out[11]:
array([Timestamp('2013-02-01 10:00:00', tz=None),
       Timestamp('2013-02-01 10:05:00', tz=None),
       Timestamp('2013-02-01 10:10:00', tz=None),
       Timestamp('2013-02-01 10:15:00', tz=None)], dtype=object)
Run Code Online (Sandbox Code Playgroud)

所以设置你的索引:

In [12]: df.index = df.index.map(lambda t: t.replace(year=2013, month=2, day=1))
Run Code Online (Sandbox Code Playgroud)

值得一提的是你可以传递一个date_parser函数read_csv,这对你来说更有意义:

In [21]: df = pd.read_csv(file_name, sep=';', parse_dates=[0], index_col=0, 
                          date_parser=lambda time: pd.Timestamp('2013/02/01 %s' % time))

In [22]: df
Out[22]:
                     val
TS
2013-02-01 10:00:00  0.1
2013-02-01 10:05:00  0.2
2013-02-01 10:10:00  0.3
2013-02-01 10:15:00  0.4
Run Code Online (Sandbox Code Playgroud)