python - 更改 Python 上 Pandas 的 date_parser 的默认日期

标签 python date pandas time

我有一个如下所示的数据集:

refrigerator.csv
08/02/2012 00:00:02;136;134
08/02/2012 00:00:03;134;134
08/02/2012 00:00:05;136;134
08/02/2012 00:00:06;136;134
08/02/2012 00:00:08;134;134
08/02/2012 00:00:09;134;134
...

我想将始终为 08/02/2012 的日期更改为 01/01/2010。我尝试执行以下操作:

import pandas as pd
refr=pd.read_csv('C:/refrigerator.csv', names=['ts', 'P1', 'P2'], 
                  sep=';', parse_dates=[0], index_col=0, 
                  date_parser=lambda x: pd.Timestamp('2010-01-01 %s' %x)) 

但是我收到了 ValueError。简而言之,我想保持时间不变,并更改日期。原因是因为我有多个数据集,每个数据集代表设备的每日功率配置文件。我不在乎日期,只在乎时间。我想以相同的日期阅读所有这些内容,以便同步它们。

最佳答案

您可以尝试先转换为 to_datetime然后在date_parser替换:

import pandas as pd
import io

temp=u"""
08/02/2012 00:00:02;136;134
08/02/2012 00:00:03;134;134
08/02/2012 00:00:05;136;134
08/02/2012 00:00:06;136;134
08/02/2012 00:00:08;134;134
08/02/2012 00:00:09;134;134"""


#after testing replace io.StringIO(temp) to filename
df =pd.read_csv(io.StringIO(temp), names=['ts', 'P1', 'P2'], 
                  sep=';', parse_dates=[0], index_col=0, 
                  date_parser=lambda x: pd.to_datetime(x).replace(year=2010, month=1,day=1))

print df
                      P1   P2
ts                           
2010-01-01 00:00:02  136  134
2010-01-01 00:00:03  134  134
2010-01-01 00:00:05  136  134
2010-01-01 00:00:06  136  134
2010-01-01 00:00:08  134  134
2010-01-01 00:00:09  134  134

关于python - 更改 Python 上 Pandas 的 date_parser 的默认日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35758054/

相关文章:

python : Create ECC Keys from private and public key represented in raw bytes

python - 在 aws 上部署 django 应用程序

python - ButtonBox 中的同质子级

Python 安装工具 : how to call function on import but not when run from script?

python - 相当于 Pandas 数据框中 R 的 'rep'

java - 从 Java 中的日历解析日期

ios - ActionSheetPickerClass , iOS

python - 通过仅提供月份或仅提供星期几来创建日期时间对象

python - Pandas - 其他每个值的列的最小值

python - 从数据集的给定日期范围中提取属于一天的数据