I have below date expressed as yearmon '202112'
I want to convert this to yearqtr and report the next quarter. Therefore from above string I want to get 2022Q1
I unsuccessfully tried below
import pandas as pd
pd.PeriodIndex(pd.to_datetime('202112') ,freq='Q')
Could you please help how to obtain the expected quarter. Any pointer will be veru helpful
CodePudding user response:
I think one issue you're running into is that '202112'
is not a valid date format. You'll want to use '2021-12'
. Then you can do something like this:
pd.to_datetime('2021-12').to_period('Q') 1
You can convert your date to this new format by simply inserting a -
at index 4 of your string like so: date[:4] '-' date[4:]
This will take your date, convert it to quarters, and add 1 quarter.
CodePudding user response:
import pandas as pd
df = pd.DataFrame({"Date": ['202112']}) # dummy data
df['next_quarter'] = pd.PeriodIndex(pd.to_datetime(df['Date'], format='%Y%m'), freq='Q') 1
print(df)
Output:
Date next_quarter
0 202112 2022Q1
Note that column Date may be a string type but Quarter will be type period. You can convert it to a string if that's what you want.