如何在pandas中将int转换为datetime并完成多日期比较?
报错原因
- 初始的
TypeError: '<' not supported between instances of 'int' and 'datetime.date'是因为参与比较的三列数据类型不一致:Text_Date列为int类型(一般存储的是类似20211008的数字格式日期),set_date和set_date_2为datetime.date类型,不同类型无法直接比较。 - 转换时触发的
ValueError是因为你手动指定了format='%Y%m%d',但Text_Date列中存在部分YYYY-MM-DD HH:MM:SS格式的字符串,和指定格式不匹配导致转换失败。
解决方案
步骤1:统一转换三列为pandas datetime类型
无需手动指定格式,让pandas自动推断不同形式的日期,同时用errors='coerce'避免非法日期直接打断执行:
# 转换Text_Date列,自动适配数字、带横杠、带时间的多种日期格式 Manual_Dialling['Text_Date'] = pd.to_datetime(Manual_Dialling['Text_Date'], errors='coerce') # 同步转换另外两个对比列,保证类型一致 Manual_Dialling['set_date'] = pd.to_datetime(Manual_Dialling['set_date'], errors='coerce') Manual_Dialling['set_date_2'] = pd.to_datetime(Manual_Dialling['set_date_2'], errors='coerce')
步骤2(可选):统一仅保留日期维度
如果不需要时间维度参与比较,可统一提取日期部分,保证三列都是datetime.date类型:
Manual_Dialling['Text_Date'] = Manual_Dialling['Text_Date'].dt.date Manual_Dialling['set_date'] = Manual_Dialling['set_date'].dt.date Manual_Dialling['set_date_2'] = Manual_Dialling['set_date_2'].dt.date
步骤3:执行原有比较逻辑
此时三列类型完全一致,np.where可以正常执行:
np.where((Manual_Dialling['Text_Date'] > Manual_Dialling['set_date']) & (Manual_Dialling['Text_Date'] < Manual_Dialling['set_date_2']), 1, 0)
内容的提问来源于stack exchange,提问作者coder_bg
相关产品推荐
相关产品推荐

