如何基于关键词列表拆分DataFrame中的描述文本
问题:拆分Pandas DataFrame中带标签的描述字段为多行
现有如下示例Pandas DataFrame:
import pandas as pd df = pd.DataFrame({ "name":['Kelly', 'David', 'Mandy', "John"], "description":[ "age: 12 gender:female hobbies: loves to read", "age:16, gender:male, hobbies: play soccer", "age: 15, gender:female, hobbies: cooking", "18, male, reading" ] })
对应的原始表格:
| name | description | |
|---|---|---|
| 0 | Kelly | age: 12 gender:female hobbies: loves to read |
| 1 | David | age:16, gender:male, hobbies: play soccer |
| 2 | Mandy | age: 15, gender:female, hobbies: cooking |
| 3 | John | 18, male, reading |
需求是:将带有age/gender/hobbies标签的description字符串拆分为多行,每个标签对应一行并保留原name关联;无明确标签的记录(如John的条目)保持原样,最终期望得到如下结果:
| name | description | |
|---|---|---|
| 0 | Kelly | age: 12 |
| 1 | Kelly | gender:female |
| 2 | Kelly | hobbies: loves to read |
| 3 | David | age:16 |
| 4 | David | gender:male |
| 5 | David | hobbies: play soccer |
| 6 | Mandy | age: 15 |
| 7 | Mandy | gender:female |
| 8 | Mandy | hobbies: cooking |
| 9 | John | 18, male, reading |
解决方案
可以通过正则表达式提取标签片段配合Pandas的explode方法实现,具体代码如下:
import re import pandas as pd # 原始DataFrame df = pd.DataFrame({ "name":['Kelly', 'David', 'Mandy', "John"], "description":[ "age: 12 gender:female hobbies: loves to read", "age:16, gender:male, hobbies: play soccer", "age: 15, gender:female, hobbies: cooking", "18, male, reading" ] }) # 定义正则,匹配三种标签对应的内容 pattern = r'(age:\s*\d+|gender:\w+|hobbies:.+?)(?=\s*(?:age:|gender:|hobbies:|$))' # 处理description字段:有标签的提取片段,无标签的保留原内容 df['description'] = df['description'].apply( lambda x: re.findall(pattern, x) if re.search(pattern, x) else [x] ) # 将列表展开为多行,重置索引 result_df = df.explode('description').reset_index(drop=True) print(result_df)
代码说明
- 正则表达式:
age:\s*\d+:匹配age标签及后续数字,允许数字前有空格gender:\w+:匹配gender标签及后续性别值hobbies:.+?:非贪婪匹配hobbies标签及后续所有内容,直到遇到下一个标签或字符串结尾(?=\s*(?:age:|gender:|hobbies:|$)):前瞻断言,确保匹配片段的边界是下一个标签或文本结尾,避免截断错误
- apply逻辑:检查每条
description是否包含目标标签,有则提取所有匹配片段组成列表,无则将原内容包装为单元素列表 - explode方法:将列表中的每个元素拆分为单独的行,自动保留对应的
name字段关联 - reset_index:重置索引,与期望结果的索引格式一致
运行代码后即可得到目标表格。
内容的提问来源于stack exchange,提问作者E.L
相关产品推荐
相关产品推荐

