【问题标题】:Pandas groupby strip timezone in indexPandas groupby 在索引中剥离时区
【发布时间】:2014-12-03 19:09:00
【问题描述】:

我遇到了一个问题,当我为唯一索引值过滤数据框时,我的时区信息被剥离(这是使用 groupby() 和 first() 完成的)。例如

import pandas as pd
import pytz

utc = pytz.utc

index = pd.date_range('20140101','20140102',freq='6H',tz=utc)
data  = pd.np.random.randint(0,10,(5,3))
namen = list('abc')

df = pd.DataFrame(data=data,index=index,columns=namen)

时区信息现在存储在索引中:

>>>df.index[0]

    Timestamp('2014-01-01 00:00:00+0000', tz='UTC')

当我只保留唯一值时,我会丢失时间戳信息。

df = df.groupby(df.index).first()

>>> df.index[0]
    Timestamp('2014-01-01 00:00:00', tz=None)

当然,我可以使用 .drop_duplicates() 来做同样的事情(.drop_duplicates() 似乎保留了时区信息),但这对我目前的工作有两个问题:

  1. drop_duplicates 不对索引进行操作,这很重要(参见 #2)
  2. 由于我的数据集的性质,我很可能在数据框中有相同的行,因此使用 drop_duplicates 将删除这些原本很好的行。

我可以通过在数据框中创建一个新列来保存索引值来使用 drop_duplicates。例如

df['dates'] = df.index
df = df.drop_duplicates(cols=['dates'])
df.pop('dates')

虽然这行得通,但看起来很草率。这里有没有我看不到的替代方案?

【问题讨论】:

  • 我没有看到这个。你用的是什么版本的 pandas、pytz 和 numpy?
  • 熊猫 0.12.0,pytz 2013b

标签: python datetime pandas timezone


【解决方案1】:

使用 pandas 0.15.1,我看不出和你做的一样:

In [90]: so_df
Out[90]: 
                           a  b  c
2014-01-01 00:00:00+00:00  3  6  2
2014-01-01 06:00:00+00:00  9  3  5
2014-01-01 12:00:00+00:00  2  9  4
2014-01-01 18:00:00+00:00  3  6  3
2014-01-02 00:00:00+00:00  4  1  4

In [93]: so_df.index[3]
Out[93]: Timestamp('2014-01-01 18:00:00+0000', tz='UTC', offset='6H')

In [94]: so_df2 = so_df.groupby(so_df.index).first()

In [95]: so_df2
Out[95]: 
                           a  b  c
2014-01-01 00:00:00+00:00  3  6  2
2014-01-01 06:00:00+00:00  9  3  5
2014-01-01 12:00:00+00:00  2  9  4
2014-01-01 18:00:00+00:00  3  6  3
2014-01-02 00:00:00+00:00  4  1  4

In [96]: so_df2.index[3]
Out[96]: Timestamp('2014-01-01 18:00:00+0000', tz='UTC', offset='6H')

0.15.0 版改进了与时区相关的several things,包括

  • 当插入到系列/数据帧中时,本地化为 UTC 的时间序列/索引将保留 UTC 时区(而不是简单的 datetime64[ns])作为 object dtype (GH8411)

希望升级能解决您的问题。请注意,从 0.15.0 开始,

pandas >= 0.15.0 将不再支持与 = 1.7.0 (GH7711)

由于您正在升级,现在可能是查看已安装版本的 pandas 的 dependencies 并升级任何可能变得有点陈旧的版本的好时机。

祝你好运!

【讨论】:

  • 更新到 15,我现在看到的结果和你一样。这让我想知道,我现在在时间戳中看到的这个“偏移量”是什么?我在快速的网络搜索中没有找到很好的解释。我知道它代表我的时间序列的频率,但有什么用?
  • @tnknepp 我不确定它扮演什么角色,除了存储有关时间序列本身的数据。
猜你喜欢
  • 1970-01-01
  • 2021-05-09
  • 1970-01-01
  • 2018-09-22
  • 2016-04-03
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多