将时区设置为熊猫数据框
Posted
技术标签:
【中文标题】将时区设置为熊猫数据框【英文标题】:Set timezone to pandas dataframe 【发布时间】:2016-05-26 19:31:58 【问题描述】:您好,我正在尝试将时区设置为数据帧,然后将其更改为 UCT 时区。
我正在读取的数据是:
Date Time;G_h
2012-03-31 23:00:00.000;0
2012-03-31 23:15:00.000;0
2012-03-31 23:30:00.000;0
2012-03-31 23:45:00.000;0
2012-04-01 00:00:00.000;0
2012-04-01 00:15:00.000;0
2012-04-01 00:30:00.000;0
2012-04-01 00:45:00.000;0
2012-04-01 01:00:00.000;0
2012-04-01 01:15:00.000;0
2012-04-01 01:30:00.000;0
我使用这个代码
df = pd.read_csv('input.csv', sep=";", index_col='Date Time', decimal=',')
df.index = pd.to_datetime(df.index, unit='s')
我的想法是使用这段代码:
df.index.tz_localize('Europe/Rome').tz_covert('UTC')
如果我尝试使用此代码设置时区'Europe/Rome'
df.index=df.index.tz_localize('Europe/Rome')
我得到这个结果:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2820, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-38-0aa69957bc90>", line 1, in <module>
d.index.tz_localize('Europe/Rome')
File "/usr/local/lib/python2.7/dist-packages/pandas/tseries/index.py", line 1608, in tz_localize
new_dates = tslib.tz_localize_to_utc(self.asi8, tz, infer_dst=infer_dst)
File "tslib.pyx", line 1981, in pandas.tslib.tz_localize_to_utc (pandas/tslib.c:29912)
AmbiguousTimeError: Cannot infer dst time from Timestamp('2012-10-28 02:00:00', tz=None), try using the 'infer_dst' argument
有什么建议吗?
我确定输入文件中时间设置正确,dst没问题!
【问题讨论】:
【参考方案1】:试试这个:
from __future__ import print_function
import pytz
import pandas as pd
from_tz = pytz.timezone('Europe/Rome')
to_tz = pytz.timezone('UTC')
df = pd.read_csv('input.csv', sep=";", index_col='Date Time', decimal=',')
df.index = pd.to_datetime(df.index, unit='s').tz_localize(from_tz).tz_convert(to_tz)
print(df)
输出:
G_h
Date Time
2012-03-31 21:00:00+00:00 0
2012-03-31 21:15:00+00:00 0
2012-03-31 21:30:00+00:00 0
2012-03-31 21:45:00+00:00 0
2012-03-31 22:00:00+00:00 0
2012-03-31 22:15:00+00:00 0
2012-03-31 22:30:00+00:00 0
2012-03-31 22:45:00+00:00 0
2012-03-31 23:00:00+00:00 0
2012-03-31 23:15:00+00:00 0
2012-03-31 23:30:00+00:00 0
【讨论】:
你有什么熊猫版本? 输入[13]:pd.__version__输出[13]:'0.13.1' 哦,我明白了。我有 0.17.1。有机会升级吗? 检查这个错误:github.com/pydata/pandas/issues/10117 和这个讨论:google.de/… 您好,很抱歉回复晚了,我已将 pandas 更新到 0.17.1,但出现此错误:df.index = pd.to_datetime(df.index, unit='s').tz_localize(from_tz) File "/usr/local/lib/python2.7/dist-packages/pandas/util/decorators.py", line 89, in wrapper return func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/pandas/tseries/index.py", line 1724, in tz_localize ambiguous=ambiguous) File "pandas/tslib.pyx", line 3781, in pandas.tslib.tz_localize_to_utc (pandas/tslib.c:64980) NonExistentTimeError: 2013-03-31 02:00:00
以上是关于将时区设置为熊猫数据框的主要内容,如果未能解决你的问题,请参考以下文章