【问题标题】:Convert a numerical relative index (=months) to datetime将数字相对索引(=月)转换为日期时间
【发布时间】:2019-06-02 16:12:36
【问题描述】:

Given 是一个 Pandas DataFrame,其数字索引表示相对月数:

df = pd.DataFrame(columns=['A', 'B'], index=np.arange(1,100))
df

    A   B
1   NaN NaN
2   NaN NaN
3   NaN NaN
... 

如何通过指定开始日期(例如,2018-11-01)将索引转换为 DateTimeIndex?

magic_function(df, start='2018-11-01', delta='month')

           A  B
2018-11-01 NaN NaN
2018-12-01 NaN NaN
2019-01-01 NaN NaN
...

我更喜欢一个也适用于任意增量的通用解决方案,例如每日或每年的系列。

【问题讨论】:

    标签: python-3.x pandas datetime time-series


    【解决方案1】:

    使用date_range

    idx=pd.date_range(start='2018-11-01',periods =len(df),freq='MS')
    df.index=idx
    

    【讨论】:

    【解决方案2】:

    我不确定是否使用 Pandas,但使用普通的 datetime 就不能这样做吗?

    import datetime start=datetime.date(2018,1,1) months = 15 adjusted = start.replace(year=start.year + int(months/12), month=months%12)

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 2020-10-05
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 2018-10-15
      • 2021-12-06
      • 2017-02-07
      • 2018-10-30
      相关资源
      最近更新 更多