You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于含Datetime的多列在Pandas中创建新列遇错求助

解决Timestamp与int无法比较的报错问题

问题背景

要基于Site Name和Date(Datetime类型)两列生成新列Active_Ind,数据及期望结果如下:

原始数据

Site NameDate
Westwood2022-11-15
Westwood2022-11-16
Northend2021-08-04
Northend2021-08-05
Northend2021-08-06

期望结果

Site NameDateActive_Ind
Westwood2022-11-150
Westwood2022-11-160
Northend2021-08-060
Northend2021-08-051
Northend2021-08-041

运行自行编写的代码时,抛出错误:< not supported between instances of 'Timestamp' and 'int'

尝试的代码:

def conditions(df):
    if (df['Site Name']=='Northend') & (df['Date'] < 2021-08-06):
        return 1
    else:
        return 0

df['Active_Ind']=df.apply(conditions,axis=1)

错误原因

你写的2021-08-06会被Python解析为整数减法运算,计算结果是2021 - 8 - 6 = 1997,而df['Date']是Timestamp类型,这两种类型无法直接用<进行比较,所以触发了报错。

解决方法

方法1:修正日期比较对象

将目标日期转换为Timestamp类型,再进行比较:

import pandas as pd

def conditions(row):
    target_date = pd.to_datetime('2021-08-06')
    if (row['Site Name'] == 'Northend') and (row['Date'] < target_date):
        return 1
    return 0

df['Active_Ind'] = df.apply(conditions, axis=1)

方法2:使用向量化操作(推荐)

apply逐行处理效率较低,用pandas的向量化条件判断更高效,代码更简洁:

import pandas as pd

target_date = pd.to_datetime('2021-08-06')
# 布尔条件直接转整数,True→1,False→0
df['Active_Ind'] = ((df['Site Name'] == 'Northend') & (df['Date'] < target_date)).astype(int)

内容的提问来源于stack exchange,提问作者David Kurtenbach

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 20:35:28