我有一个如下所示的数据集:
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/