Turn 2010 Q1 to datetime as 2010-3-31

风流意气都作罢 提交于 2019-12-20 05:13:29

问题


How to find a smart solution to turn Year_Q to datetime? I tried to use

pd.to_datetime(working_visa_nationality['Year_Q'])

but got error says that this cannot be recognized. So I tried a stupid way as:

working_visa_nationality['Year'] = working_visa_nationality.Year_Q.str.slice(0,4)
working_visa_nationality['Quarter'] = working_visa_nationality.Year_Q.str.slice(6,8)

And now I found a problem: it is true that I can groupby data by the year, but it is difficult to include the quarter to my line plot.

So how to make 2010 Q1 like 2010-3-31?


回答1:


I a bit changed MaxU answer:

df = pd.DataFrame({'Year_Q': ['2010 Q1', '2015 Q2']})

df['Dates']  = pd.PeriodIndex(df['Year_Q'].str.replace(' ', ''), freq='Q').to_timestamp()
print (df)
    Year_Q      Dates
0  2010 Q1 2010-01-01
1  2015 Q2 2015-04-01

EDIT:

df['Dates']  = pd.PeriodIndex(df['Year_Q'].str.replace(' ', ''), freq='Q').to_timestamp(how='e')
print (df)
    Year_Q      Dates
0  2010 Q1 2010-03-31
1  2015 Q2 2015-06-30



回答2:


My solution with regex.

df['Year_Q'] = pd.to_datetime(df['Year_Q'].str.replace(r'\ [Q1]+', '-3-31'))



回答3:


working_visa_nationality['Dates']  = pd.PeriodIndex(working_visa_nationality['Year_Q'].str.replace(' ', ''), freq='Q').to_timestamp() + pd.offsets.QuarterEnd()

working_visa_nationality['Dates']  = pd.PeriodIndex(working_visa_nationality['Year_Q'].str.replace(' ', ''), freq='Q').to_timestamp(how='end')

both of them work well. Thank you all and I did some experiment.



来源:https://stackoverflow.com/questions/52053955/turn-2010-q1-to-datetime-as-2010-3-31

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