pandas Lambda应用于查找两个日期之间的差异

ddrv8njm  于 2022-12-09  发布在  其他
关注(0)|答案(1)|浏览(225)

我尝试使用apply方法和lambda来查找两个日期之间的月份。我当前遇到一个属性错误:
属性错误:'datetime.date'对象没有属性'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)

你觉得我哪里做错了吗?

9nvpjoqh

9nvpjoqh1#

从文档中:

Series具有一个访问器,用于简洁地返回日期时间,类似于Series值的属性(如果它是类似Series的日期时间/期间)。这将返回一个Series,其索引类似于现有Series。

因此,在调用pandas.Series.apply时,不需要使用.dt访问器,因为它可以单独访问每个元素(已经是datetime)。因此,出现以下错误(取决于Series的类型):

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。因此,要转换一个数字/int,可以使用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

相关问题