Converting PeriodIndex to DateTimeIndex?

前端 未结 2 1195
野趣味
野趣味 2020-12-31 18:57

I have a question regarding converting a tseries.period.PeriodIndex into a datetime.

I have a DataFrame which looks like this:

               colors      c         


        
相关标签:
2条回答
  • 2020-12-31 19:04

    You can use the to_timestamp method of PeriodIndex for this:

    In [25]: pidx = pd.period_range('2012-01-01', periods=10)
    
    In [26]: pidx
    Out[26]:
    <class 'pandas.tseries.period.PeriodIndex'>
    [2012-01-01, ..., 2012-01-10]
    Length: 10, Freq: D
    
    In [27]: pidx.to_timestamp()
    Out[27]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2012-01-01, ..., 2012-01-10]
    Length: 10, Freq: D, Timezone: None
    

    In older versions of Pandas the method was to_datetime

    0 讨论(0)
  • 2020-12-31 19:12

    You can also use the following to get exactly the same result.

    idx.astype('datetime64[ns]') 
    

    To convert back to period, you can do:

     idx.to_period(freq='D')
    
    0 讨论(0)
提交回复
热议问题