【问题标题】:How to use pandas.to_datetime with "strange" strings formats如何使用带有“奇怪”字符串格式的 pandas.to_datetime
【发布时间】:2019-07-14 11:00:27
【问题描述】:

我正在尝试使用 pandas.to_datetime 将 pandas 数据框的列从字符串类型转换为日期时间。 col 的值具有以下格式:

17 年第一季度

其中“Q”是一年中的第一个季度,“17”是 2017 年。

我在该列中也有空值(我可以删除日期为空的整行)。

我试图解决它,消除季度并仅考虑年份,但我无法通过这种方式将 16 年转换为 2016 年:

df_cpu["Launch_Date"] = [str(x) for x in df_cpu["Launch_Date"]]
df_cpu["Launch_Date"] = [x[3:5] for x in df_cpu["Launch_Date"]]
df_cpu["Launch_Date"] = [int(x) for x in df_cpu["Launch_Date"]]
df_cpu["Launch_Date"] = pd.to_datetime(df_cpu["Launch_Date"],    format('%Y'))

即使这样也行不通:

df_cpu["Launch_Date"] = pd.to_datetime(df_cpu["Launch_Date"], format('Q*\'%Y'))

因为我得到这个错误:

ValueError: ('Unknown string format:', "Q3'16")

我应该如何解决这个问题?

我想要以下类型的输出:例如,如果值为“Q1'16”,我想要“01-01-2016”。

【问题讨论】:

    标签: python pandas datetime dataframe machine-learning


    【解决方案1】:

    考虑:

    1) 提供的数据:

    df_cpu = pd.DataFrame(["Q1'17","Q3'16"], columns=['Launch_Date'])
    

    2) 发布日期列的长度始终为 5;

    您可以使用pd.offsets.QuarterBegin() 将季度添加到一年的第一天:

    >> pd.to_datetime(df_cpu.Launch_Date.str[3:5],format='%y') + np.multiply(pd.offsets.QuarterBegin(startingMonth=1), df_cpu.Launch_Date.str[1:2].values.astype(int)-1)
    0   2017-01-01
    1   2016-07-01
    Name: Launch_Date, dtype: datetime64[ns]
    

    【讨论】:

      【解决方案2】:

      我不是日期时间格式转换方面的专家,但这里有一个可行的解决方案。我不能说它是最有效的。我会编写一个函数,以您喜欢的格式返回日期时间,在数据帧上使用“应用”方法。

      请注意,下面的函数假定年份始终为 20--,并且输出为字符串。根据需要更改输出数据类型。

      def new_date(arr):
          if isinstance(arr, str):
              quarter = {'Q1':'01-01-', 'Q2':'04-01-', 'Q3':'07-01-', 'Q4':'10-01-'}
              x, y = arr.split("'")[0], arr.split("'")[1]
              x_new = quarter[x]
              y_new = '20'+y
              return x_new + y_new
          else:
              pass
      
      df_cpu["Launch_Date"] = df_cpu["Launch_Date"].apply(new_date)
      

      另请注意,“is_instance”条件仅用于处理 NaN 值。如果您使用 pd.dropna(),则不需要。

      【讨论】:

        【解决方案3】:

        你可以将map字符串的第一部分改为一个可以在to_datetime之后使用的值如:

        df_cpu = pd.DataFrame({'Launch_Date':["Q1'17", "Q3'16"]})
        dict_Q = {"Q1": '01-01-', "Q3": '07-01-'}
        
        print (pd.to_datetime( df_cpu["Launch_Date"].str[:2].map(dict_Q) #replace Qx by a first of month
                               + df_cpu["Launch_Date"].str[3:])) #get the year independtly
        
        0   2017-01-01
        1   2016-07-01
        Name: Launch_Date, dtype: datetime64[ns]
        

        并且不要忘记将 Q2 和 Q4 int dict_Q 添加到您想要的正确值

        【讨论】:

          猜你喜欢
          • 2020-03-15
          • 2023-03-20
          • 2013-04-02
          • 1970-01-01
          • 2023-04-02
          • 2021-04-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多