如何找到将Year_Q转换为日期时间的智能解决方案?我尝试使用
pd.to_datetime(working_visa_nationality['Year_Q'])
但出现错误,表明无法识别。所以我尝试了一种愚蠢的方式:
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)
现在我发现了一个问题:确实可以按年份对数据进行分组,但是很难将四分之一包括在我的线图中。
那么如何使2010年第一季度像2010-3-31?
答案 0 :(得分:1)
我有点改变了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
编辑:
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
答案 1 :(得分:0)
我使用正则表达式的解决方案。
df['Year_Q'] = pd.to_datetime(df['Year_Q'].str.replace(r'\ [Q1]+', '-3-31'))
答案 2 :(得分:0)
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')
他们两个都很好。
谢谢大家,我做了一些实验。