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

基于DataFrame两列特定条件创建分类新列的技术问询

Pandas DataFrame 按指定配对规则创建新列

需求说明

我有一个包含PPT、1、2三列的DataFrame,需要创建新列3,规则如下:

  • 当列1为A且列2为1、列1为B且列2为2、列1为C且列2为3时,新列取值为YES
  • 其余所有情况取值为NO

输入输出示例

输入表格

PPT12
1A1
2A2
3A3
4B1
5B2
6B3
7C1
8C2
9C3

输出表格

PPT123
1A1YES
2A2NO
3A3NO
4B1NO
5B2YES
6B3NO
7C1NO
8C2NO
9C3YES

解决方案

方法1:使用numpy.where组合多条件

这种方法直接通过逻辑运算符组合条件,效率较高,适合大数据集:

import pandas as pd
import numpy as np

# 构造输入DataFrame
df = pd.DataFrame({
    'PPT': [1, 2, 3, 4, 5, 6, 7, 8, 9],
    '1': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
    '2': [1, 2, 3, 1, 2, 3, 1, 2, 3]
})

# 创建新列3
df['3'] = np.where(
    ((df['1'] == 'A') & (df['2'] == 1)) |
    ((df['1'] == 'B') & (df['2'] == 2)) |
    ((df['1'] == 'C') & (df['2'] == 3)),
    'YES',
    'NO'
)

方法2:通过配对元组检查

如果需要扩展更多配对规则,这种方法更易维护,直接修改目标配对列表即可:

import pandas as pd

df = pd.DataFrame({
    'PPT': [1, 2, 3, 4, 5, 6, 7, 8, 9],
    '1': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
    '2': [1, 2, 3, 1, 2, 3, 1, 2, 3]
})

# 定义符合条件的配对
target_pairs = [('A', 1), ('B', 2), ('C', 3)]
# 逐行检查配对是否在目标列表中
df['3'] = df.apply(lambda row: 'YES' if (row['1'], row['2']) in target_pairs else 'NO', axis=1)

方法3:使用isin结合配对列

这种方法通过构造配对列,利用isin批量判断,代码更简洁:

import pandas as pd

df = pd.DataFrame({
    'PPT': [1, 2, 3, 4, 5, 6, 7, 8, 9],
    '1': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
    '2': [1, 2, 3, 1, 2, 3, 1, 2, 3]
})

target_pairs = [('A', 1), ('B', 2), ('C', 3)]
# 构造配对列
df['pair'] = list(zip(df['1'], df['2']))
# 判断并映射结果
df['3'] = df['pair'].isin(target_pairs).map({True: 'YES', False: 'NO'})
# 清理临时列
df.drop('pair', axis=1, inplace=True)

以上三种方法都能得到需求中的输出结果,可根据数据集大小和维护需求选择合适的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:55:16