【问题标题】:Turn 2010 Q1 to datetime as 2010-3-31将 2010 Q1 转换为日期时间为 2010-3-31
【发布时间】:2019-02-02 20:32:58
【问题描述】:

如何找到将 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 Q1 像 2010-3-31 一样呢?

【问题讨论】:

标签: python pandas time-series data-cleaning


【解决方案1】:
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')

它们都运行良好。 谢谢大家,我做了一些实验。

【讨论】:

    【解决方案2】:

    我的正则表达式解决方案。

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

    【讨论】:

      【解决方案3】:

      我有点变了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
      

      【讨论】:

      • 太棒了!但是如何使日期成为季度最后一天的结束? 2010-01-01 ->2010-03-31
      • @ZakkYang - 检查已编辑的答案,需要参数 how
      猜你喜欢
      • 2014-09-23
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      相关资源
      最近更新 更多