基于含Datetime的多列在Pandas中创建新列遇错求助
解决Timestamp与int无法比较的报错问题
问题背景
要基于Site Name和Date(Datetime类型)两列生成新列Active_Ind,数据及期望结果如下:
原始数据
| Site Name | Date |
|---|---|
| Westwood | 2022-11-15 |
| Westwood | 2022-11-16 |
| Northend | 2021-08-04 |
| Northend | 2021-08-05 |
| Northend | 2021-08-06 |
期望结果
| Site Name | Date | Active_Ind |
|---|---|---|
| Westwood | 2022-11-15 | 0 |
| Westwood | 2022-11-16 | 0 |
| Northend | 2021-08-06 | 0 |
| Northend | 2021-08-05 | 1 |
| Northend | 2021-08-04 | 1 |
运行自行编写的代码时,抛出错误:< 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
相关产品推荐
相关产品推荐

