【问题标题】:Pandas insert row into dataframe with timezone-aware index熊猫使用时区感知索引将行插入数据帧
【发布时间】:2021-11-18 04:31:18
【问题描述】:

我有一个具有时区感知索引的数据框,当我尝试将新行插入此数据框时,它不起作用,而是将索引的类型更改为'object'(即,它可以'不将行添加到当前类型中)。

MRE 如下:

import pandas as pd

df = pd.DataFrame({"time": ["2021/06/06 12:00:00"], "col1": [2]})
df.index = pd.to_datetime(df['time'])
df = df.drop('time', axis=1)
df.index = df.index.tz_localize('UTC')

# Doesn't work, index is now 'object' as this is considered a string
# row = pd.Series(name='2021/06/05 12:00:00')
# df = df.append(row)


# Also doesn't work, as timezones differ
row = pd.Series(name=pd.Timestamp('2021/06/05 12:00:00'))
df = df.append(row)

print(df.index)

我知道我可以执行以下操作:

tz = df.index[0].tz
row = pd.Series(name=pd.Timestamp('2021/06/05 12:00:00', tz=tz))

但是我怀疑当单位不同时这是否会起作用,或者甚至可能是熊猫Timestamp我不知道的其他一些属性,所以理想情况下希望完全复制Timestamp配置我插入的新时间戳的索引。

如果有人碰巧知道如何在此数据框中插入新行,同时保持索引类型不变,将不胜感激。

【问题讨论】:

  • 为什么不分配tzin Timestamp: pd.Series(name=pd.Timestamp('2021/06/05 12:00:00', tz = "UTC"))?

标签: python pandas dataframe datetimeindex


【解决方案1】:

由于DatetimeTZ 仅支持单个时区,因此关键是确保新的Timestamp 始终与您现有的df.index.tz 匹配。

插入新的Timestamp时:


示例

  • 鉴于您的 MRE df:

    df
    #                            col1
    # time                           
    # 2021-06-06 12:00:00+00:00     2
    
    df.index.dtype
    # datetime64[ns, UTC]
    
  • 如果您知道新的Timestamp 与tz 相同,只需像您提到的那样在构造函数中设置它:

    ts1 = pd.Timestamp('2021/06/05 12:00:00', tz=df.index.tz)
    df.loc[ts1] = 4
    #                            col1
    # time                           
    # 2021-06-06 12:00:00+00:00     2
    # 2021-06-05 12:00:00+00:00     4
    
    df.index.dtype
    # datetime64[ns, UTC]
    
  • 如果您的新 Timestamp 位于不同的 tz(这是您的主要关注点),请使用 astimezone 将其转换(例如,从美国东部返回到 UTC):

    ts2 = pd.Timestamp('2021/06/05 12:00:00', tz='US/Eastern').astimezone(df.index.tz)
    df.loc[ts2] = 6
    #                            col1
    # time                           
    # 2021-06-06 12:00:00+00:00     2
    # 2021-06-05 12:00:00+00:00     4
    # 2021-06-05 16:00:00+00:00     6
    
    df.index.dtype
    # datetime64[ns, UTC]
    
  • 请注意,我使用的是loc,因为它更快更简单,但append 仍然有效:

    ts3 = pd.Timestamp('2021/06/05 12:00:00', tz='US/Central').astimezone(df.index.tz)
    row = pd.Series([8], name=ts3, index=['col1'])
    df = df.append(row)
    #                            col1
    # time                           
    # 2021-06-06 12:00:00+00:00     2
    # 2021-06-05 12:00:00+00:00     4
    # 2021-06-05 16:00:00+00:00     6
    # 2021-06-05 17:00:00+00:00     8
    
    df.index.dtype
    # datetime64[ns, UTC]
    

【讨论】:

    【解决方案2】:

    Timestamp 对象肯定属于'object' 类型,如果使用Timestamps 作为索引,则可能无法转义索引以采用此类型。

    通过“时间戳配置”,我理解“时区”,并且您想在同一时区中插入新时间。

    • 您从一开始就知道时区,所有行的数据都来自已知来自同一时区的来源。在这种情况下,您可以在实例化 Timestamps 时指定相同的时区。

    • 或者您首先不知道数据的时区,并且您有来自另一个来源的新数据,因此可能来自不同的时区,您当然知道。混合来自不同时区的时间戳不是问题,因为在将它们相互比较时应该考虑时区。您仍然可以稍后将它们全部本地化到您喜欢的时区。

    【讨论】:

      【解决方案3】:

      你也可以这样做。 DateTimeIndexes 是对象。

      for time_zone in ['MST', 'EST', 'GMT']:
              row = pd.Timestamp('2021/06/05 12:00:00', tz=time_zone)
              df.loc[row] = 1
      
      # to whichever timezone you want
      df.index = pd.to_datetime(df.index, utc=True).tz_convert('EST')
      

      【讨论】:

        猜你喜欢
        • 2020-02-20
        • 1970-01-01
        • 2014-11-13
        • 2017-10-12
        • 2021-05-08
        • 1970-01-01
        • 2020-11-07
        • 1970-01-01
        • 2020-08-22
        相关资源
        最近更新 更多