我正在尝试将数据帧的时间索引作为一个系列获取,但当我调用方法 to_series 时,它似乎正在删除时区。下面是一个例子。这是错误还是我做错了什么?
rows = 50
df = pd.DataFrame(np.random.randn(rows,2), columns=list('AB'), index=pd.date_range('1/1/2000', periods=rows, freq='1H', tz=pytz.UTC))
print df.index[-1]
# 2000-01-03 01:00:00+00:00
print df.index.to_series()[-1]
# 2000-01-03 01:00:00
print df.index[-1].tzinfo
# UTC
print df.index.to_series()[-1].tzinfo
#None
最佳答案
不,你没有做错什么,也不是错误。
这是 pandas/numpy 的当前已知限制:仅在索引中支持时区感知日期时间数据。在系列中,数据存储为 numpy datetime64
类型,不支持时区。将此时区功能也添加到系列中存在一个 Unresolved 问题:https://github.com/pydata/pandas/issues/8260
解决方法是将数据存储为 object
dtype 而不是 datetime64
(然后它们将存储为 Timestamp
对象, 日期时间.日期时间
)。这将使您能够保留时区信息。
to_series
有一个 keep_tz
关键字参数来获取它(参见 docstring ):
In [34]: df = df.tz_convert('US/Eastern')
In [35]: df.index.to_series()[-1]
Out[35]: Timestamp('2000-01-03 01:00:00')
In [36]: df.index.to_series(keep_tz=True)[-1]
Out[36]: Timestamp('2000-01-02 20:00:00-0500', tz='US/Eastern', offset='H')
关于python - Pandas 时区感知索引在转换为系列时会降低时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28565965/