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

如何在Python数据框中用if/or语句按指定逻辑创建新列

需求与解决方案

需求说明

需要为DataFrame新增一列Assign Number 1 or 2,赋值规则如下:

  • 当Posting Archived At (GMT)处于2022年1月至6月之间,且Profile Archive Reason为Offer Declined*或Withdrawn时,赋值1
  • 当Posting Archived At (GMT)处于2022年7月至12月之间,且Profile Archive Reason为Offer Declined*或Withdrawn时,赋值2
  • 其他情况赋值0

初始代码问题

你提供的初始代码存在两处问题:

  1. 语法错误:Python中判断相等需用==,而非=
  2. 未处理日期区间的判断逻辑,仅校验了归档原因

解决方案

步骤1:确保日期列为datetime类型

首先需要将Posting Archived At (GMT)转换为datetime格式,才能提取月份进行区间判断:

import pandas as pd

# 假设原日期格式为"January 22"(月份全称+两位年份)
df['Posting Archived At (GMT)'] = pd.to_datetime(df['Posting Archived At (GMT)'], format='%B %y')

步骤2:生成目标列(推荐向量化操作,效率更高)

使用numpy.where嵌套实现多条件判断:

import numpy as np

# 定义两个核心条件
cond1 = (df['Posting Archived At (GMT)'].dt.month.between(1, 6)) & \
        (df['Profile Archive Reason'].isin(['Offer Declined*', 'Withdrawn']))
cond2 = (df['Posting Archived At (GMT)'].dt.month.between(7, 12)) & \
        (df['Profile Archive Reason'].isin(['Offer Declined*', 'Withdrawn']))

# 按条件赋值
df['Assign Number 1 or 2'] = np.where(cond1, 1, np.where(cond2, 2, 0))

备选方案:使用apply(适合复杂逻辑,小数据集可用)

如果需要更直观的逻辑写法,可使用apply方法:

def get_assign_number(row):
    reason = row['Profile Archive Reason']
    date_month = row['Posting Archived At (GMT)'].month
    if reason in ['Offer Declined*', 'Withdrawn']:
        if 1 <= date_month <= 6:
            return 1
        elif 7 <= date_month <= 12:
            return 2
    return 0

df['Assign Number 1 or 2'] = df.apply(get_assign_number, axis=1)

注意事项

  • 请确保Profile Archive Reason中的字符串与代码中的完全匹配(比如注意Offer Declined*末尾是否有空格)
  • 如果原日期格式与假设不同,需调整pd.to_datetime中的format参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 15:31:11