【问题标题】:Converting Pandas DatetimeIndex to a numeric format将 Pandas DatetimeIndex 转换为数字格式
【发布时间】:2018-03-12 02:45:00
【问题描述】:

我想将我的 DataFrame 中的 DatetimeIndex 转换为浮点格式,可以在我的模型中进行分析。有人可以告诉我该怎么做吗?我需要使用 date2num() 函数吗? 非常感谢!

【问题讨论】:

    标签: python pandas datetime type-conversion


    【解决方案1】:

    转换为Timedelta 并从dt.total_seconds 中提取总秒数:

    df
    
            date
    0 2013-01-01
    1 2013-01-02
    2 2013-01-03
    3 2013-01-04
    4 2013-01-05
    5 2013-01-06
    6 2013-01-07
    7 2013-01-08
    8 2013-01-09
    9 2013-01-10
    
    pd.to_timedelta(df.date).dt.total_seconds()
    
    0    1.356998e+09
    1    1.357085e+09
    2    1.357171e+09
    3    1.357258e+09
    4    1.357344e+09
    5    1.357430e+09
    6    1.357517e+09
    7    1.357603e+09
    8    1.357690e+09
    9    1.357776e+09
    Name: date, dtype: float64
    

    或者,也许将数据显示为int 类型会更有用:

    pd.to_timedelta(df.date).dt.total_seconds().astype(int)
    
    0    1356998400
    1    1357084800
    2    1357171200
    3    1357257600
    4    1357344000
    5    1357430400
    6    1357516800
    7    1357603200
    8    1357689600
    9    1357776000
    Name: date, dtype: int64
    

    【讨论】:

    • 尝试一次 df.date.values.astype(float)
    • @Bharathshetty cannot astype a datetimelike from [datetime64[ns]] to [float64]
    • 我认为你有一个错误的解决方案尝试pd.to_datetime(pd.to_timedelta(df.date).dt.total_seconds().values[0])它给了1970 ...
    • @Bharathshetty 这就是函数的工作原理。它不明白数字是时代。解决方案没有错。你应该明白 1970 年的纪元时间是 0,那是贝尔实验室开发 Unix OS 的时间——因此得名“Unix Timestamp”。
    • 我只是认为 op 想要 datetime 的浮点表示。我不知道OP在现实中想要什么。让我们看看他什么时候回来
    【解决方案2】:

    使用 astype float 即如果你有一个像

    这样的数据框
    df = pd.DataFrame({'date': ['1998-03-01 00:00:01', '2001-04-01 00:00:01','1998-06-01 00:00:01','2001-08-01 00:00:01','2001-05-03 00:00:01','1994-03-01 00:00:01'] })
    df['date'] = pd.to_datetime(df['date'])
    df['x'] = list('abcdef')
    df = df.set_index('date')
    

    然后

    df.index.values.astype(float)
    
    array([  8.88710401e+17,   9.86083201e+17,   8.96659201e+17,
         9.96624001e+17,   9.88848001e+17,   7.62480001e+17])
    
    pd.to_datetime(df.index.values.astype(float))
    
    DatetimeIndex(['1998-03-01 00:00:01', '2001-04-01 00:00:01',
               '1998-06-01 00:00:01', '2001-08-01 00:00:01',
               '2001-05-03 00:00:01', '1994-03-01 00:00:01'],
              dtype='datetime64[ns]', freq=None)
    

    【讨论】:

    • 请注意,自 2017 年的纪元以来的秒数为 10e9,因此 10e17 不正确。查看stackoverflow.com/a/46502880/4909087 并运行stackoverflow.com/questions/4548684/…
    • 但是当您将其转换回 pd.to_datetime 时,原始日期会返回 na
    • 是的,但我认为 OP 想要使用纪元时间。我不知道 astype 给出了什么,但它似乎是一个错误?这绝对不是时代。
    • 使用 timedelta 时出现 AttributeError
    • 哦,对不起。我从一个日期时间列开始。让我修改一下。
    【解决方案3】:

    我找到了另一个解决方案:

    df['date'] = df['date'].astype('datetime64').astype(int).astype(float)
    

    【讨论】:

    • 我已经检查过了,它对我有用。你能说更多关于你的问题吗?对我来说 df['date'] 有 dtype: object,因为我是从 csv 读取的。也许这就是区别。你可以试试这个:df['date'].astype(int).astype(float)
    • 如果您在列中存储datetime.date 对象,直接转换为浮点数将失败。 Date 对象可以转换为datetime64 以获得数字表示所需的分辨率,但这些对象可能不会转换为浮点值,因此需要转换为 int 的中间步骤。
    • 使用astype(int)会引发警告,建议使用.view(int):flatten_df['first_year_date'].astype('datetime64').view(int).astype(float)
    【解决方案4】:

    我相信这提供了另一种解决方案,这里假设一个带有 DatetimeIndex 的数据框。

    pd.to_numeric(df.index, downcast='float')
    # although normally I would prefer an integer, and to coerce errors to NaN
    pd.to_numeric(df.index, errors = 'coerce',downcast='integer')
    

    【讨论】:

      【解决方案5】:

      如果您只想要 DateTimeIndex 的特定部分,试试这个:

      ADDITIONAL = 1
      ddf_c['ts_part_numeric'] = ((ddf_c.index.dt.year * (10000 * ADDITIONAL)) + (ddf_c.index.dt.month * (100 * ADDITIONAL)) + ((ddf_c.index.dt.day) * ADDITIONAL))
      

      输出是

      20190523
      20190524
      

      可以根据您需要的时间分辨率进行调整。

      【讨论】:

        猜你喜欢
        • 2018-10-02
        • 2015-03-15
        • 2018-06-23
        • 2016-11-23
        • 1970-01-01
        • 1970-01-01
        • 2022-11-21
        • 2012-10-01
        • 2020-04-28
        相关资源
        最近更新 更多