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

Python正则提取pandas DataFrame中{}内数值无分组报错求助

问题原因

pandas的str.extractall()方法要求正则表达式必须包含至少一个捕获组(即用小括号包裹的匹配片段),你修改后的正则只有前后断言规则,没有给要提取的内容加捕获括号,所以触发了「pattern contain no group」报错。

修复后可运行代码

import pandas as pd

# 测试用DataFrame
df = pd.DataFrame([["{1} | | Had a Greeter welcome clients {1.0}     | | Take measures to ensure a safe and organized distribution {1.000}         | | Protected confidentiality of clients (on social media, pictures, in conversation, own congregation members receiving assistance, etc.)",
                    "{1.00}  | | Chairs for clients to sit in while waiting {1.0000}     | | Take measures to ensure a safe and organized distribution"],
                   ["{1  } | Financial literacy/budgeting {1   } | | Monetary/Bill Support {1}    | | Mental Health Services/Counseling",
                    "{1}| | Clothing Assistance {1       }  | | Healthcare {1}    | | Mental Health Services/Counseling {1}     | | Spiritual Support {1}      | | Job Skills Training"]
                    ] , columns = ['CF1', 'CF2'])

# 核心逻辑修正版
result = (
    df.stack()
    .str.extractall(r'(?<=\{)([\d+\.\ ]+)(?=\})') # 给目标匹配段加捕获括号
    [0]
    .str.strip() # 清除匹配到的前后冗余空格
    .astype(float) # 先转浮点数兼容小数点格式
    .astype(int) # 再转整数求和
    .groupby(level=[0,1])
    .sum()
    .unstack()
)

运行后输出结果:

索引CF1CF2
032
135

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:24:02