我尝试使用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)
你觉得我哪里做错了吗?
1条答案
按热度按时间9nvpjoqh1#
从文档中:
Series具有一个访问器,用于简洁地返回日期时间,类似于Series值的属性(如果它是类似Series的日期时间/期间)。这将返回一个Series,其索引类似于现有Series。
因此,在调用
pandas.Series.apply
时,不需要使用.dt
访问器,因为它可以单独访问每个元素(已经是datetime
)。因此,出现以下错误(取决于Series的类型):请尝试以下操作:
或者使用矢量代码:
这将返回一个
pandas.tseries.offsets.DateOffset
。因此,要转换一个数字/int,可以使用operator.attrgetter
将名称作为属性: