python - Pandas 从长到宽而不会失去时区意识

标签 python pandas timezone reshape

我正在尝试将 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

enter image description here

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

enter image description here

关于python - Pandas 从长到宽而不会失去时区意识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39496573/

相关文章:

python - numpy数组中的like语句时如何编写案例

python - 使用特定日期时间索引重新索引 Pandas Dataframe

python - 在 Django Admin 中将 ManyToManyField 显示为复选框

python - 如何使用 & 连接条件来过滤 Pandas 数据框?

python - 将数据帧写入 csv 按列

Java 8 : DateTimeFormatter not translating timezone based on locale

python - 如何同时遍历多个列表?

python - 如何从 timedelta 中删除微秒

c# - 如何在 C# 中将字符串偏移量转换为时间跨度

c# - 判断某个时区的时间是否在一个范围内