我正在尝试将 pandas 数据框从长格式 reshape 为宽格式,但时间戳丢失了时区。
这是一个可重现的例子:
import pandas as pd
long = pd.DataFrame(dict(
ind=[1,1,2, 2],
events=['event1', 'event2', 'event1', 'event2'],
time=[pd.Timestamp('2015-03-30 00:00:00', tz='UTC'),
pd.Timestamp('2015-03-30 01:00:00', tz='UTC'),
pd.Timestamp('2015-03-30 02:00:00', tz='UTC'),
pd.Timestamp('2015-03-30 03:00:00', tz='UTC')]))
然后在查看 long.time
时,我得到了一个时区感知系列。
0 2015-03-30 00:00:00+00:00
1 2015-03-30 01:00:00+00:00
2 2015-03-30 02:00:00+00:00
3 2015-03-30 03:00:00+00:00
Name: time, dtype: datetime64[ns, UTC]
像这样 reshape 之后
wide = long.set_index(['ind'] + ['events']).unstack(level=1).reset_index()
时区消失了。例如。 wide.time.event1
0 2015-03-30 00:00:00
1 2015-03-30 02:00:00
Name: event1, dtype: datetime64[ns]
是否有另一种不丢失时区的 reshape 方式?
最佳答案
pandas
正在跟踪时区。当您 unstack
时, reshape 一定发生在 numpy
中,它会失去踪迹。证明了这一点
df = pd.concat([long.time, pd.Series(long.time.values)],
axis=1, keys=['pandas', 'numpy'])
df
df.dtypes
pandas datetime64[ns, UTC]
numpy datetime64[ns]
dtype: object
解决方法是将每一列重铸为您关心的 dtype
for c, col in wide.filter(like='time').iteritems():
wide[c] = col.astype(long.time.dtype)
wide
关于python - Pandas 从长到宽而不会失去时区意识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39496573/