Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change date of a DateTimeIndex

Tags:

python

pandas

I have a csv file named data.csv such as

TS;val
10:00;0.1
10:05;0.2
10:10;0.3
10:15;0.4

I read this csv file using this script

#!/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)

I get this

                     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

I would like to change date of every DateTimeIndex to 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

What is the easier way to do this ?

like image 307
scls Avatar asked Jun 17 '13 16:06

scls


1 Answers

Timestamps have a replace method (just like datetimes):

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)

So set your index to this:

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

Worth mentioning that you can pass in a date_parser function to read_csv, which might make more sense for you:

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
like image 88
Andy Hayden Avatar answered Oct 04 '22 17:10

Andy Hayden