[英]Lambda Apply to find difference between two dates
我正在嘗試對 lambda 使用 apply 方法來查找兩個日期之間的月份。 我目前遇到屬性錯誤:
AttributeError: 'datetime.date' object 沒有屬性 'dt'
我的前期轉換:
df['date1'] = pd.to_datetime(df['date1'], errors='ignore', infer_datetime_format=True)
df['date2'] = pd.to_datetime(df['date2'], errors='ignore', infer_datetime_format=True)
這是我的街區:
df['Duration (Months)'] = df.apply(lambda x: x["Date1"].dt.to_period('M').astype(int) - x["Date2"].dt.to_period('M').astype(int), axis=1)
第二次嘗試:
df['Duration (Months)'] = df['date1'].dt.to_period('M').astype(int) - df['date2'].dt.to_period('M').astype(int)
關於我哪里出錯的任何想法?
從文檔中:
Series有一個訪問器,可以簡潔地返回類似於 Series 值的日期時間屬性,如果它是類似於 Series 的日期時間/時間段。 這將返回一個系列,索引與現有系列相同。
因此,在調用pandas.Series.apply
時無需使用.dt
訪問器,因為它可以單獨訪問每個元素(已經是datetime
)。 因此出現以下錯誤(取決於您系列的類型):
AttributeError: 'datetime.date' object has no attribute 'dt'
AttributeError: 'Timestamp' object has no attribute 'dt'
試試這個:
(df.apply(lambda x: x["date1"].to_period('M') - x["date2"].to_period('M'), axis=1))
或者使用矢量代碼:
(df["date1"].dt.to_period('M') - df["date2"].dt.to_period("M")) #here, we needed the .dt accessor
0 <0 * MonthEnds>
1 <-1 * MonthEnd>
2 <6 * MonthEnds>
dtype: object
這將返回pandas.tseries.offsets.DateOffset
。 因此,要轉換一個數字/整數,您可以使用operator.attrgetter
來獲取名稱作為屬性:
from operator import attrgetter
(df["date1"].dt.to_period('M') - df["date2"].dt.to_period("M")).apply(attrgetter("n"))
0 0
1 -1
2 6
dtype: int64
使用的輸入:
date1 date2
0 2022-01-13 2022-01-01
1 2022-02-05 2022-03-06
2 2022-10-14 2022-04-09
date1 datetime64[ns]
date2 datetime64[ns]
dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.