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() )
运行后输出结果:
| 索引 | CF1 | CF2 |
|---|---|---|
| 0 | 3 | 2 |
| 1 | 3 | 5 |
内容的提问来源于stack exchange,提问作者BeginnerProgrammer
相关产品推荐
相关产品推荐

