Skip to content Skip to sidebar Skip to footer

Pandas: Converting Index Of YYYYQQ Values To Datetime Object

I have the following DataFrame: df = pd.DataFrame({'A':[1,2,3],'B':[4,3,2]},index = ['201701','201702','201703']) where the index of string values are dates in the format YYYYQQ (

Solution 1:

Use

In [2325]: [pd.to_datetime(x[:4]) + pd.offsets.QuarterBegin(int(x[5:])) for x in df.index]
Out[2325]:
[Timestamp('2017-03-01 00:00:00'),
 Timestamp('2017-06-01 00:00:00'),
 Timestamp('2017-09-01 00:00:00')]

Solution 2:

I'd use Pandas Period:

In [92]: x = pd.PeriodIndex(df.index.astype(str).str.replace(r'0(\d)$', r'q\1'), freq='Q')

In [93]: x
Out[93]: PeriodIndex(['2017Q1', '2017Q2', '2017Q3'], dtype='period[Q-DEC]', freq='Q-DEC')

In [94]: x.to_timestamp()
Out[94]: DatetimeIndex(['2017-01-01', '2017-04-01', '2017-07-01'], dtype='datetime64[ns]', freq='QS-OCT')

Post a Comment for "Pandas: Converting Index Of YYYYQQ Values To Datetime Object"