【问题标题】:In Python/Pandas how do I convert century-months to DateTimeIndex?在 Python/Pandas 中,如何将世纪月转换为 DateTimeIndex?
【发布时间】:2014-09-05 20:28:04
【问题描述】:

我正在使用一个数据集,该数据集将日期编码为自 1899 年 12 月以来的整数月数,因此第 1 个月是 1900 年 1 月,第 1165 个月是 1997 年 1 月。我想转换为 pandas DateTimeIndex。到目前为止,我想出的最好的是:

month0 = np.datetime64('1899-12-15')
one_month = np.timedelta64(30, 'D') + np.timedelta64(10.5, 'h')
birthdates = pandas.DatetimeIndex(month0 + one_month * resp.cmbirth)

开始日期为每月 15 日,时间增量为 30 天 10.5 小时,即一个日历月的平均长度。所以一个月内的日期会偏移一两天。

所以这似乎有点 hacky,我想知道是否有更好的方法。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用内置的pandas 日期时间功能。

    import pandas as pd
    import numpy as np
    
    indexed_months = np.random.random_integers(0, high=1165, size=100)
    month0 = pd.to_datetime('1899-12-01')
    date_list = [month0 + pd.DateOffset(months=mnt) for mnt in indexed_months]
    birthdates = pd.DatetimeIndex(date_list) 
    

    我假设您的 resp.cmbirth 对象看起来像一个介于 0 和 1165 之间的整数数组。

    我不太清楚为什么您希望索引的 bin 边缘从月初或月底偏移。可以这样做:

    shifted_birthdates = birthdates.shift(15, freq=pd.datetools.day)
    

    如果你愿意,同样可以持续几个小时。此SO question 和相关pandas github issue 的答案中也有有用的信息。

    【讨论】:

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