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?

帅比萌擦擦* 提交于 2021-02-11 13:44:38

问题


  **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 didnt wwork. Result dataframe should have 'Year_qtr' column as date values instead of object.


回答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 do
df['datetime'].dt.to_period("Q")
# 0    1947Q1
# 1    1947Q2
# 2    1948Q3
# 3    1949Q4
# Name: datetime, dtype: period[Q-DEC]



回答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'))


来源:https://stackoverflow.com/questions/62922662/how-do-you-convert-a-column-containing-year-quarter-in-a-str-format-as-1947q1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!