Skip to content Skip to sidebar Skip to footer

How Do You Convert A Column Containing Year & Quarter In A Str Format As '1947q1' To Date Format Column Where Both Year And Quarter Are Considered?

**Year_qtr GDP ADJ_GDP** 2 1947q1 243.1 1934.5 3 1947q2 246.3 1932.3 4 1948q3 250.1 1930.3 5 1949q4 260.3 1960.7 Tried parse() from dateutil package but

Solution 1:

pandas already can do this out of the box! you can cast to datetime right away:

import pandas as pd

df = pd.DataFrame({'Year_qtr': ['1947q1', '1947q2', '1948q3', '1949q4']})

df['datetime'] = pd.to_datetime(df['Year_qtr'])

# df#   Year_qtr   datetime# 0   1947q1 1947-01-01# 1   1947q2 1947-04-01# 2   1948q3 1948-07-01# 3   1949q4 1949-10-01# vice versa you can dodf['datetime'].dt.to_period("Q")
# 0    1947Q1# 1    1947Q2# 2    1948Q3# 3    1949Q4# Name: datetime, dtype: period[Q-DEC]

Solution 2:

You can't store quarter in a datetime object. You can have them separately:

# Split year and quarter information
year, quarter = map(int, year_column.split('q'))

Post a Comment for "How Do You Convert A Column Containing Year & Quarter In A Str Format As '1947q1' To Date Format Column Where Both Year And Quarter Are Considered?"