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

Pandas DataFrame按条件添加Check列失败及KeyError问题求助

问题解决:为DataFrame添加条件判断的Check列

需求说明

需要为DataFrame新增名为Check的列,满足以下任一条件时标记为Correct,否则为Fail:

  • Info列包含Suppression total(含拼写变体Suppression totale)且Type列包含SUP - SDM
  • Info列包含Suppression partiel且Type列包含Franc SUP - Geisi

原始DataFrame

TypeInfo
Sup_EF - SUP - SDM2021-12-08 16:47:51.0-Suppression totale
Modif_EF - SUP - SDM2021-12-08 16:47:51.0-Creation
Sup_EF - SUP - Geisi2021-12-08 16:47:51.0-Suppression totale
Modif_EF - Franc SUP - Geisi2021-12-17 10:50:40.0-Suppression partiel

期望输出

TypeInfoCheck
Sup_EF - SUP - SDM2021-12-08 16:47:51.0-Suppression totalCorrect
Modif_EF - SUP - SDM2021-12-08 16:47:51.0-CreationFail
Sup_EF - SUP - Geisi2021-12-08 16:47:51.0-Suppression totalFail
Modif_EF - Franc SUP - Geisi2021-12-17 10:50:40.0-Suppression partielCorrect

错误代码分析

第一段代码问题

if ('SUP - SDM' in df["Type"].values) and ('Suppression total' in df['Info'].values):
    df['Check'] = "Correct"
elif ('Franc SUP - Geisi' in df["Type"].values) and ('Suppression partiel' in df['Info'].values):
    df['Check'] = "Correct"
else:
    df['Check'] = "Fail"

核心错误是逐列判断而非逐行判断:in df["Type"].values是检查整个列是否存在目标字符串,不是针对每行做条件验证。只要整列存在符合条件的值,就会把所有行的Check设为Correct,否则全设为Fail,完全不符合逐行匹配的需求。

第二段代码问题

df['Check'] = df.apply(lambda x: 'Correct' if ('Suppression total' in x['Info'] and 'Sup-SDM' in x['Type']) or ('Suppression partiel' in x['Info'] and 'Franc SUP - Geisi' in x['Type']) else 'Fail')
  • KeyError: 'Info'是因为apply默认按列处理(axis=0),此时x代表列而非行,找不到'Info'键,需指定axis=1实现逐行处理。
  • 字符串匹配偏差:需求中的Sup-SDM实际是SUP - SDM(含空格),Info列存在Suppression totale的拼写,这些偏差会导致匹配失败。

正确解决方案

方法1:修正后的apply逐行处理

指定axis=1遍历每行,同时兼容拼写变体:

df['Check'] = df.apply(
    lambda row: 'Correct' 
    if ('Suppression total' in row['Info'] or 'Suppression totale' in row['Info']) and 'SUP - SDM' in row['Type'] 
       or 'Suppression partiel' in row['Info'] and 'Franc SUP - Geisi' in row['Type']
    else 'Fail',
    axis=1
)

方法2:布尔索引(更高效)

利用pandas向量化操作,避免循环,效率更高:

import numpy as np

# 定义两个条件,正则兼容拼写变体
cond1 = df['Info'].str.contains('Suppression total(e)?', regex=True) & df['Type'].str.contains('SUP - SDM')
cond2 = df['Info'].str.contains('Suppression partiel') & df['Type'].str.contains('Franc SUP - Geisi')

# 合并条件并赋值
df['Check'] = np.where(cond1 | cond2, 'Correct', 'Fail')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 11:33:44