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

如何基于关键词列表拆分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"
    ]
})

对应的原始表格:

namedescription
0Kellyage: 12 gender:female hobbies: loves to read
1Davidage:16, gender:male, hobbies: play soccer
2Mandyage: 15, gender:female, hobbies: cooking
3John18, male, reading

需求是:将带有age/gender/hobbies标签的description字符串拆分为多行,每个标签对应一行并保留原name关联;无明确标签的记录(如John的条目)保持原样,最终期望得到如下结果:

namedescription
0Kellyage: 12
1Kellygender:female
2Kellyhobbies: loves to read
3Davidage:16
4Davidgender:male
5Davidhobbies: play soccer
6Mandyage: 15
7Mandygender:female
8Mandyhobbies: cooking
9John18, 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)

代码说明

  1. 正则表达式:
    • age:\s*\d+:匹配age标签及后续数字,允许数字前有空格
    • gender:\w+:匹配gender标签及后续性别值
    • hobbies:.+?:非贪婪匹配hobbies标签及后续所有内容,直到遇到下一个标签或字符串结尾
    • (?=\s*(?:age:|gender:|hobbies:|$)):前瞻断言,确保匹配片段的边界是下一个标签或文本结尾,避免截断错误
  2. apply逻辑:检查每条description是否包含目标标签,有则提取所有匹配片段组成列表,无则将原内容包装为单元素列表
  3. explode方法:将列表中的每个元素拆分为单独的行,自动保留对应的name字段关联
  4. reset_index:重置索引,与期望结果的索引格式一致

运行代码后即可得到目标表格。


内容的提问来源于stack exchange,提问作者E.L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:15:37