R F Ramadanti
R F Ramadanti

Reputation: 33

How can I convert string of year and quarter number into the period[Q-DEC] datatype in Python?

I have a dataframe with column formatted as a string with value such as '20151' to identify year and quarter, just like '2015Q1'.

I need it to be in DateTime format, specifically period[Q-DEC] datatype. Only by looking at the value, that '2015Q1' is already the right format, but it is actually a string.

The additional problem is I don't have information of the date, only the period as a string. How can I convert that string into the period[Q-DEC] datatype in Python?

Upvotes: 1

Views: 975

Answers (1)

Gustav Rasmussen
Gustav Rasmussen

Reputation: 3961

Convert to the Pandas Period type like this:

import pandas as pd

d = "20151"
t = d[:-1] + "Q" + d[-1:]
month = pd.Period(t, freq="M")
print(month)

returns:

2015-01

Conversely, if you need the PeriodIndex:

values = ["2015Q1", "2015Q2", "2015Q3", "2015Q4"]
index = pd.PeriodIndex(values, freq="Q")
print(index)

Will return:

PeriodIndex(['2015Q1', '2015Q2', '2015Q3', '2015Q4'], dtype='period[Q-DEC]', freq='Q-DEC')

Upvotes: 1

Related Questions