代码之家  ›  专栏  ›  技术社区  ›  nilsinelabore

AttributeError:“Timedelta”对象没有属性“dt”

  •  0
  • nilsinelabore  · 技术社区  · 4 年前

    我有一个 df :

        id  timestamp                       data  group Date
    27001   27242   2020-01-01 09:07:21.277 19.5    1   2020-01-01
    27002   27243   2020-01-01 09:07:21.377 19.0    1   2020-01-01
    27581   27822   2020-01-02 07:53:05.173 19.5    1   2020-01-02
    27582   27823   2020-01-02 07:53:05.273 20.0    1   2020-01-02
    27647   27888   2020-01-02 10:01:46.380 20.5    1   2020-01-02
    ...
    

    我想以秒为单位计算第1行和第2行之间的时间差。我可以用

    df['timediff'] = (df['timestamp'].shift(-1) - df['timestamp']).dt.total_seconds()
    

    然而,当我放大只看2行,即row1和row0时,用代码:

    difference = (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).dt.total_seconds()
    

    它返回错误

    AttributeError:“Timedelta”对象没有属性“dt”

    为什么会这样?

    0 回复  |  直到 4 年前
        1
  •  4
  •   Chicodelarose    4 年前

    经检查,以下为 Series :

    type(df['timestamp'].shift(-1) - df['timestamp'])
    

    系列有一个访问器( dt )用于日期时间类属性的对象。然而,以下是 TimeDelta 没有dt访问器:

    type(df.loc[0, 'timestamp'] - df.loc[1, 'timestamp'])
    

    只需拨打以下电话(无需 dt 访问器)来解决错误:

    difference = (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).total_seconds()
    
        2
  •  4
  •   pedrobin    3 年前

    如果你最终来到这里,想抽出几天时间: (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).days

        3
  •  2
  •   Shubham Sharma mkln    4 年前

    正如@hpaulj在评论中所说, dt 仅与 dataframe 像物体。

    因此,为了获得 total seconds 你必须使用 difference = (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).total_seconds()