Date Modified DateTimeIndex

I have a csv file called data.csv like

 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 it

  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 want to change the date of each 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 easier to do?

+6
source share
3 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 for this index:

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

It is worth mentioning that you can pass the date_parser function to read_csv , which may make more sense to 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 
+8
source

provide date_parser

 In [50]: pd.read_csv(StringIO(data), sep=';', parse_dates=[0], index_col=0, date_parser=lambda x: Timestamp('20130201 %s' % x)) Out[50]: 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 
+1
source

I see two ways to do this. The first one is the simplest: use 'string'.split(' ') . For the string bb jj it will return a list of two elements bb and jj , so just get the first element.

The second option is to create a datetime string object from the string and reformat it the way you want. In my opinion, this solution is better. If you need a different format tomorrow, it will be much easier. To do this: use the strptime function described here: http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime

Then, to return a string from a datetime object, simply use the strftime function . The whole format is available here: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

0
source

Source: https://habr.com/ru/post/947487/


All Articles