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

如何修正Pandas提取字符串列信息时结果带列表括号的问题?

解决Pandas文本提取结果为列表格式的问题

问题背景

我有一个Pandas DataFrame,其中difference列的内容示例如下:

Backward compatibility errors (2):
error at original_source=specs/994.json, in API POST /echo api path removed without deprecation [api-path-removed-without-deprecation]. 

error at original_source=specs/994.json, in API GET /users/{username} api path removed without deprecation [api-path-removed-without-deprecation]. 

需要从该列提取三类信息:

  • 将Backward compatibility errors提取至errors字段
  • 将括号内的数字提取至count字段(转为整数类型)
  • 将方括号内的内容提取至content字段(多个匹配项用逗号分隔)

当前代码能提取信息,但结果均为列表格式(带[]),需要优化:

优化后的代码

import pandas as pd
import re

df['difference'] = df['difference'].astype(str)

# 修正正则表达式,确保匹配完整目标内容
keywords_regex = {
    'errors': r'([A-Za-z\s]+ errors)',  # 匹配包含空格的完整错误类型
    'count': r'\((\d+)\)',             # 匹配括号内的数字
    'content': r'\[(.*?)\]'            # 匹配方括号内的内容
}

def extract_keywords(text):
    keywords = {}
    for name, regex in keywords_regex.items():
        matches = re.findall(regex, text)
        if name == 'count':
            # 提取数字并转为整数,无匹配则设为0
            keywords[name] = int(matches[0]) if matches else 0
        elif name == 'errors':
            # 提取完整错误类型,无匹配则设为空字符串
            keywords[name] = matches[0].strip() if matches else ''
        elif name == 'content':
            # 多个匹配项用逗号分隔,无匹配则设为空字符串
            keywords[name] = ', '.join(matches) if matches else ''
    return pd.Series(keywords)

# 应用函数并生成新列
df[list(keywords_regex.keys())] = df['difference'].apply(extract_keywords)

关键修改说明

  1. 修正正则表达式:原errors字段的正则r'(\w+ errors)'只能匹配单个单词加errors,改为r'([A-Za-z\s]+ errors)'后可以匹配带空格的完整错误类型(比如Backward compatibility errors)。
  2. 处理列表结果:
    • count:每个文本只会有一个数字,取匹配列表的第一个元素并转为整数,避免空匹配报错。
    • errors:取第一个匹配项并去除首尾空格,得到干净的错误类型名称。
    • content:如果有多个方括号内容(比如示例中的两个),用逗号连接成字符串,替代默认的列表格式。
  3. 空值处理:添加无匹配时的默认值,避免索引越界错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:44:56