簡體   English   中英

來自 to_datetime() 的奇怪行為

[英]Strange behavior from to_datetime()

我在這里真的過得很艱難。

我的 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

我的目標是將“購買日期”列從字符串更改為日期時間 object,以便我可以通過應用此 function 來運行群組分析:

      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')

function 返回錯誤: 'str' object 沒有屬性 'year'我嘗試了以下功能並使用了所有 arguments (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

請幫忙

所以,你幾乎在那里:

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

該錯誤與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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM