How to convert dates to quarters in Python?

Pandas has a method to help you, it's called pd.PeriodIndex(monthcolumn, freq= 'Q'). You may need to convert your month column to datatype first by using datetime libray.

Pandas also have a method called 'to_date' that you can use to convert a column to a date column.

For example:

df["year"] = pd.to_date(df["year"])

datecolumn.dt.quarter feature will help.

df.date = pd.to_datetime(df.date)
df["Quarter"] = df.date.dt.quarter

Series.dt.to_period

import pandas as pd
df['date'] = pd.to_datetime(df['date'])

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

         date quarter
s1 2018-03-22  2018Q1
s2 2018-03-22  2018Q1
s1 2018-06-22  2018Q2
s2 2018-06-22  2018Q2
s1 2018-09-22  2018Q3
s2 2018-09-22  2018Q3

to_datetime:

df.date = pd.to_datetime(df.date)

PeriodIndex

df['quarter'] = pd.PeriodIndex(df.date, freq='Q')

         date quarter
s1 2018-03-22  2018Q1
s2 2018-03-22  2018Q1
s1 2018-06-22  2018Q2
s2 2018-06-22  2018Q2
s1 2018-09-22  2018Q3
s2 2018-09-22  2018Q3