简体   繁体   English

如何比较 python 中的两个日期列

[英]how to compare two date columns in python

still learning python and have a previous SAS background.还在学习 python 并且有以前的 SAS 背景。 Want to compare two date columns and have a string column based on the result.想要比较两个日期列并根据结果创建一个字符串列。

example is below示例如下

在此处输入图像描述

essentially, if fee_paid_date is before close date, then say"fee paid before closed" else "fee paid during open"本质上,如果 fee_paid_date 在关闭日期之前,则说“关闭前支付的费用”,否则说“打开期间支付的费用”

so here is what i did所以这就是我所做的

main_df["Payment_validity"] = main_df['fee_paid_date'].apply(lambda x: 'Fee paid while open' if x <=main_df['PACKAGE_D_CLOSE'] else 'Fee paid after closed ')

and i get the following error:我收到以下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Any help is much appreciated任何帮助深表感谢

Use axis=1 to tell do the apply row wise使用axis=1告诉apply行明智

main_df["Payment_validity"] = main_df[['PACKAGE_D_CLOSE','fee_paid_date']].apply(lambda x: 'Fee paid while open' if x[1] <= x[0] else 'Fee paid after closed ', axis=1)

NOTE: assuming PACKAGE_D_CLOSE and fee_paid_date are datetime object not string .注意:假设PACKAGE_D_CLOSEfee_paid_datedatetime时间 object 而不是string

You can cast them to datetime by simply您可以通过简单地将它们转换为datetime时间

main_df['fee_paid_date'] = pd.to_datetime(main_df['fee_paid_date'])
main_df['PACKAGE_D_CLOSE'] = pd.to_datetime(main_df['PACKAGE_D_CLOSE'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM