【问题标题】:Pandas groupby datatime index, possible bugPandas groupby 日期时间索引,可能的错误
【发布时间】:2017-01-16 20:26:35
【问题描述】:

我有一个 Pandas DataFrame,其中有一列是 tz 感知时间戳,我尝试分组(级别 = 0).first()。我得到一个不正确的结果。我错过了什么还是熊猫错误?

x = pd.DataFrame(index = [1,1,2,2,2], data = pd.date_range("7:00", "9:00", freq="30min", tz = 'US/Eastern'))

In [58]: x
Out[58]: 


     0
1 2016-09-08 07:00:00-04:00
1 2016-09-08 07:30:00-04:00
2 2016-09-08 08:00:00-04:00
2 2016-09-08 08:30:00-04:00
2 2016-09-08 09:00:00-04:00

In [59]: x.groupby(level=0).first()
Out[59]: 
                          0
1 2016-09-08 11:00:00-04:00
2 2016-09-08 12:00:00-04:00

【问题讨论】:

  • 它看起来像一个错误...... Pandas 将时间戳转换为 UTC,但它也保留了旧的 TZ 信息......
  • 绝对是一个错误。

标签: python pandas timestamp


【解决方案1】:

我不认为这是一个错误。如果您浏览pytz 文档,则清楚地表明对于美国/东部时区,无法指定夏令时结束时间转换之前/之后。

在这种情况下,坚持使用 UTC 似乎是最好的选择。

摘自docs

 Be aware that timezones (e.g., pytz.timezone('US/Eastern')) are not
 necessarily equal across timezone versions. So if data is localized to
 a specific timezone in the HDFStore using one version of a timezone
 library and that data is updated with another version, the data will
 be converted to UTC since these timezones are not considered equal.
 Either use the same version of timezone library or use tz_convert with
 the updated timezone definition.

转换可以如下进行:

答:使用tz_localize 方法将naive/time-aware datetime 本地化为UTC

data = pd.date_range("7:00", "9:00", freq="30min").tz_localize('UTC')

B:使用tz_convert方法转换pandas对象进行转换 tz 感知数据到另一个时区。

df = pd.DataFrame(index=[1,1,2,2,2], data=data.tz_convert('US/Eastern'))
df.groupby(level=0).first()

导致:

                          0
1 2016-09-09 07:00:00-04:00
2 2016-09-09 08:00:00-04:00

#0    datetime64[ns, US/Eastern]
#dtype: object

【讨论】:

    【解决方案2】:

    这实际上是这里报告的 pandas 错误:

    https://github.com/pydata/pandas/issues/10668

    【讨论】:

      猜你喜欢
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 2017-08-13
      • 1970-01-01
      • 2015-12-08
      • 2018-04-21
      相关资源
      最近更新 更多