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 mention DateTimeIndex.quarter
format='%Y%q'
does not work. Neither does the option on='%Y%q
Use DataFrame. style. format() and Lambda Function to Change datetime Format. You can also use the DataFrame.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With