Converting String to Date [with year and quarter]

I have a pandas dataframe where one column contains a row for year and quarter in the following format:

2015Q1

My question is: How to convert this to two datetime columns, one per year and one per quarter.

+4
source share
2 answers

You can use split, then direct the column yearto intand, if necessary, add Qto the column Q:

df = pd.DataFrame({'date':['2015Q1','2015Q2']})
print (df)
     date
0  2015Q1
1  2015Q2

df[['year','q']] = df.date.str.split('Q', expand=True)
df.year = df.year.astype(int)
df.q = 'Q' + df.q
print (df)
     date  year   q
0  2015Q1  2015  Q1
1  2015Q2  2015  Q2

Also you can use Period:

df['date'] = pd.to_datetime(df.date).dt.to_period('Q')

df['year'] = df['date'].dt.year
df['quarter'] = df['date'].dt.quarter

print (df)
    date  year  quarter
0 2015Q1  2015        1
1 2015Q2  2015        2
+7
source

You can also build a datetimeIndex and name the year and quarter on it.

df.index = pd.to_datetime(df.date)
df['year'] = df.index.year
df['quarter'] = df.index.quarter

              date  year  quarter
date                             
2015-01-01  2015Q1  2015        1
2015-04-01  2015Q2  2015        2

, , datetimeIndex, ​​, : df.groupby(df.index.quarter)

+1

Source: https://habr.com/ru/post/1660957/


All Articles