Need to rename convert string or datetime to quarter in Pandas?
If so, you may use the following syntax to extract quarter info from your DataFrame:
df['Date'].dt.to_period('Q')
The picture below demonstrate it:
To begin, let's create a simple DataFrame with a datetime column:
import pandas as pd
dates = ['2021-01-01', '2021-05-02', '2021-08-03']
df = pd.DataFrame({'StartDate': dates})
df['StartDate'] = pd.to_datetime(df['StartDate'])
df
StartDate |
---|
2021-01-01 |
2021-05-02 |
2021-08-03 |
Step 1: Extract Quarter as YYYYMM from DataTime Column in Pandas
Let's say that you want to extract the quarter info in the next format: YYYYMM
. Pandas offers a built-in method for this purpose .dt.to_period('Q')
:
df['quarter'] = df['StartDate'].dt.to_period('Q')
the result would be:
0 2021Q1
1 2021Q2
2 2021Q3
Step 2: Extract Quarter(custom format) from DataTime Column in Pandas
What if you like to get a custom format instead of the default one? In this case you can use method: dt.strftime('q%q %y\'')
to change the format like:
df['quarter_custom'] = df['StartDate'].dt.to_period('Q').dt.strftime('q%q %y\'')
This will output:
0 q1 21'
1 q2 21'
2 q3 21'
Another option for custom formatting might be separated extraction of the information as:
df['StartDate'].dt.year.astype(str) + '-' + df['StartDate'].dt.quarter.astype(str)
Step 3: Extract Quarters without the year
If you need to analyse the quarter info without the year information you can get it by:
df['StartDate'].dt.quarter