【问题标题】:Pandas long to wide without losing timezone awareness熊猫从长到宽而不会失去时区意识
【发布时间】:2016-09-14 17:40:18
【问题描述】:

我正在尝试将 pandas 数据帧从长格式重塑为宽格式,并且时间戳会丢失时区。

这是一个可重现的例子:

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]

像这样重塑之后

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]

是否有另一种不丢失时区的重塑方式?

【问题讨论】:

    标签: python pandas timezone reshape


    【解决方案1】:

    pandas 正在跟踪时区。当您unstack 时,这种重塑必须发生在失去轨道的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
    

    【讨论】:

    • @kael 更新帖子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 2021-09-04
    • 2020-08-06
    • 2021-02-09
    相关资源
    最近更新 更多