Formatting Quarter time in pandas columns

22,568

You can use to_period("Q"):

df.index = df.index.to_period("Q")

import pandas as pd
df = pd.DataFrame({"y": [1,2,3]}, 
                  index=pd.to_datetime(["2000-03-31 00:00:00", "2000-05-31 00:00:00", "2000-08-31 00:00:00"]))

df.index = df.index.to_period("Q")
df
#       y
#2000Q1 1
#2000Q2 2
#2000Q3 3

To convert a normal column col, use dt to access the Datetime objects in the series:

df = pd.DataFrame({"y": [1,2,3], 'col': pd.to_datetime(["2000-03-31 00:00:00", "2000-05-31 00:00:00", "2000-08-31 00:00:00"])})


df['col'] = df['col'].dt.to_period("Q")

df
#      col  y
#0  2000Q1  1
#1  2000Q2  2
#2  2000Q3  3
Share:
22,568
B Furtado
Author by

B Furtado

Pythonist into agent-based modeling. Urban economics. Policy

Updated on July 05, 2022

Comments