Turn 2010 Q1 to datetime as 2010-3-31

后端 未结 3 796
南旧
南旧 2021-01-24 13:44

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

相关标签:
3条回答
  • 2021-01-24 14:20

    My solution with regex.

    df['Year_Q'] = pd.to_datetime(df['Year_Q'].str.replace(r'\ [Q1]+', '-3-31'))
    
    0 讨论(0)
  • 2021-01-24 14:26
    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.

    0 讨论(0)
  • 2021-01-24 14:31

    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
    
    0 讨论(0)
提交回复
热议问题