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

如何在Python DataFrame中拆分ID列逻辑条件以获取目标格式结果

拆分DataFrame中逻辑条件ID列的实现方案

问题背景

需要拆分Python DataFrame中ID列的逻辑条件:将or连接的项归入Or列,&连接的项归入And列,但现有代码无法得到预期结果。

现有尝试代码

df['and'] = df['ID'].str.extract(r'\((.*?)\)', expand = False)
df['test'] = np.where(df['ID'].str.contains('or'), df['ID'].str.split('or'), None)

当前输出

IDNoteandtest
A or B or (C & D)NaNC & D[A , B , (C & D)]
E or F & (G & H)NaNG & H[E , F & (G & H)]
W or X or Y or ZNaNNaN[W , X , Y , Z]

预期输出

IDNoteAndOr
A or B or (C & D)C, DA, B
E or F & (G & H)F, G, HE
W or X or Y or ZW, X, Y, Z

解决方案

通过自定义函数处理每个ID字符串,分别提取or和&关联的元素,再合并到原DataFrame中:

完整实现代码

import pandas as pd
import re

# 构造示例DataFrame
data = {
    'ID': ['A or B or (C & D)', 'E or F & (G & H)', 'W or X or Y or Z'],
    'Note': [None, None, None]
}
df = pd.DataFrame(data)

def split_logic_condition(s):
    or_items = []
    and_items = []
    
    # 按'or'拆分字符串并去除前后空格
    parts = [p.strip() for p in s.split('or')]
    
    for part in parts:
        if '&' in part:
            # 去除括号后按'&'拆分,提取所有and关联元素
            cleaned_part = re.sub(r'[\(\)]', '', part)
            and_subitems = [item.strip() for item in cleaned_part.split('&')]
            and_items.extend(and_subitems)
        else:
            # 无&关联的元素直接归入or组
            or_items.append(part)
    
    # 转换为逗号分隔的字符串,空值返回空字符串
    return {
        'And': ', '.join(and_items) if and_items else '',
        'Or': ', '.join(or_items) if or_items else ''
    }

# 应用函数并合并结果
result_df = df['ID'].apply(lambda x: pd.Series(split_logic_condition(x)))
df = pd.concat([df, result_df], axis=1)
# 调整列顺序并填充空值
df = df[['ID', 'Note', 'And', 'Or']]
df['Note'] = df['Note'].fillna('')

print(df)

代码说明

  1. 拆分逻辑:先按or拆分整个字符串,对每个子部分判断是否包含&:
    • 含&的子部分:去除括号后按&拆分,将所有元素收集到And组
    • 不含&的子部分:直接归入Or组
  2. 结果整合:用apply将自定义函数应用到每行,将结果转为DataFrame列后合并到原表,最后调整列顺序并填充空值。

运行后将得到与预期完全一致的输出。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:43:09