更改DateTimeIndex的日期 [英] Change date of a DateTimeIndex

查看:58
本文介绍了更改DateTimeIndex的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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)

我明白了

                     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

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

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

更简单的方法是什么?

推荐答案

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

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))

值得一提的是,您可以将date_parser函数传递给 read_csv ,这可能对您更有意义:

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

这篇关于更改DateTimeIndex的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆