Skip to content Skip to sidebar Skip to footer

Mutating Columns Of Months And Years Together Into A Column Of Quarter And Year In Python

I have a dataframe df = {'Month': [1, 8], 'Year': [2015, 2020]} df = pd.DataFrame(data = df) df Would like to mutate it as a new column. Desired output: df = {'Month': [1, 8], 'Ye

Solution 1:

the basic idea is to convert to datetime and the convert to_period with Q as Quarter (you can still optimize this I think)

df['Quarter'] = (pd.to_datetime(df[['Month','Year']].astype(str)
                   .agg('-'.join,1).radd("01-"),dayfirst=True).dt.to_period('Q'))

Or a simpler and better way as @Ben.T commented:

df['Quarter'] = pd.to_datetime(df[['Month','Year']].assign(day=1)).dt.to_period('Q')
print(df)

MonthYear Quarter
0120152015Q1
1820202020Q3

Solution 2:

df['Quarter'] = df[['Year', 'Month']].astype(str).apply('-'.join,1)
df['Quarter'] = pd.PeriodIndex(pd.to_datetime(df['Quarter']), freq ='Q')

Post a Comment for "Mutating Columns Of Months And Years Together Into A Column Of Quarter And Year In Python"