I have a DataFrame
with columns in DateTime
index, representing quarters such as:
2000-03-31 00:00:00
How can I do to transform this into '2000q1'?
I have looked around the docs, but they only say DateTimeIndex.quarter Here: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.quarter.html
format='%Y%q'
does not work. Neither does the option on='%Y%q
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