【问题标题】:Strange behavior from to_datetime()来自 to_datetime() 的奇怪行为
【发布时间】:2020-05-03 11:40:50
【问题描述】:

我真的在这里度过了一段艰难的时光。

我的 DataFrame 是这样的

     Purchase_Date     Customer_ID  Gender  
0   2012-12-18 00:00:00   7223        F 
1   2012-12-20 00:00:00   7841        M     
2   2012-12-21 00:00:00   8374        F

我的目标是将“购买日期”列从字符串更改为日期时间对象,以便我可以通过应用此函数来运行同期群分析:

      def get_month(x): return dt.datetime(x.year, x.month, 1)
      data['InvoiceMonth'] = data['Purchase_Date'].apply(get_month)
      grouping = data.groupby('Customer_ID')['InvoiceMonth']
      data['CohortMonth'] = grouping.transform('min')

函数返回错误:'str'对象没有属性'year' 我尝试了以下函数并使用了所有参数(dayfirst、yearfirst...)

data["Purchase_Date"] = pd.to_datetime(data["Purchase_Date"])
pd.to_datetime()
datetime.datetime.strptime()

我不断收到 ValueError: day is out of range for month

请帮忙

【问题讨论】:

    标签: python pandas time-series string-to-datetime


    【解决方案1】:

    那么,你就快到了:

    data["Purchase_Date"] = pd.to_datetime(data["Purchase_Date"])
    data['InvoiceMonth'] = data["Purchase_Date"].dt.strftime("%Y-%m-01")
    

    (以object 格式输出月份 - 您可以通过添加pd.to_datetime(...) 将其转换为datetime

    或者 - 使用您的方法:

    data["Purchase_Date"] = pd.to_datetime(data["Purchase_Date"])
    
    import datetime as dt
    
    def get_month(x): return dt.datetime(x.year, x.month, 1)
    
    data['InvoiceMonth'] = data["Purchase_Date"].apply(get_month)
    

    (输出月份为datetime

    两者都会返回,尽管我强烈推荐第一个选项:

      Purchase_Date  Customer_ID Gender InvoiceMonth
    0    2012-12-18         7223      F   2012-12-01
    1    2012-12-20         7841      M   2012-12-01
    2    2012-12-21         8374      F   2012-12-01
    

    【讨论】:

      【解决方案2】:

      该错误与get_month 有关,因为首先您需要将Purchase_Date 转换为日期时间系列:

      import datetime as dt
      data.Purchase_Date = pd.to_datetime(data.Purchase_Date, format='%Y-%m-%d %H:%M:%S')
      data['Purchase_Date'].apply(get_month)
      
      # 0   2012-12-01
      # 1   2012-12-01
      # 2   2012-12-01
      

      您也可以使用MonthBegin 获取InvoiceMonth,这样您就不必声明get_month

      from pd.tseries.offset import MonthBegin
      
      data.Purchase_Date = pd.to_datetime(data.Purchase_Date, format='%Y-%m-%d %H:%M:%S')
      data['InvoiceMonth'] = data.Purchase_Date - MonthBegin(1)
      
      data['InvoiceMonth']
      # 0   2012-12-01
      # 1   2012-12-01
      # 2   2012-12-01
      

      【讨论】:

        猜你喜欢
        • 2020-02-10
        • 2014-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多