基于字符串前缀与merge id更新DataFrame中的列表值
问题描述
我有一个DataFrame,其中某列存储着字符串列表,需要将信息缺失的行的值替换为同merge id分组下其他行的对应完整值。待更新的字符串会匹配目标完整字符串的首个甚至前两个单词,更新规则按merge id分组执行。
原始数据
| merge id | values |
|---|---|
| 1 | [apple] |
| 1 | [apple tree, river fish 123] |
| 1 | [river] |
| 2 | [foo bar 111] |
| 2 | [foo bar, apple 888] |
| 2 | [apple] |
对应初始化代码:
import pandas as pd df = pd.DataFrame({ 'merge id': [1, 1, 1, 2, 2, 2], 'values': [['apple'], ['apple tree', 'river fish 123'], ['river'], ['foo bar 111'], ['foo bar', 'apple 888'], ['apple']] })
期望输出
| merge id | values |
|---|---|
| 1 | [apple tree] |
| 1 | [apple tree, river fish 123] |
| 1 | [river fish 123] |
| 2 | [foo bar 111] |
| 2 | [foo bar 111, apple 888] |
| 2 | [apple 888] |
解决方案
通过按merge id分组建立关键词映射,再批量替换的方式实现需求:
- 按
merge id分组,收集组内所有完整字符串,建立关键词到完整字符串的映射:- 对每个完整字符串,优先提取前两个单词作为关键词(若存在),再提取单个单词作为关键词
- 确保长关键词(前两个单词)的映射优先级高于短关键词,避免覆盖正确匹配项
- 遍历每组的每行数据,将
values列表中的短字符串替换为映射对应的完整字符串
具体代码实现:
import pandas as pd def process_group(group): # 收集分组内所有完整字符串 all_strings = [] for lst in group['values']: all_strings.extend(lst) # 建立关键词映射:优先匹配前两个单词,再匹配单个单词 mapping = {} for s in all_strings: words = s.split() # 前两个单词作为关键词(字符串长度足够时) if len(words) >= 2: key = ' '.join(words[:2]) mapping[key] = s # 单个单词作为关键词,仅当未被长关键词覆盖时添加 key = words[0] if key not in mapping: mapping[key] = s # 替换每行values列表中的元素 group['values'] = group['values'].apply( lambda lst: [mapping.get(item, item) for item in lst] ) return group # 按merge id分组处理数据 df_updated = df.groupby('merge id', group_keys=False).apply(process_group) # 输出结果 print(df_updated)
运行后输出与期望一致:
merge id values 0 1 [apple tree] 1 1 [apple tree, river fish 123] 2 1 [river fish 123] 3 2 [foo bar 111] 4 2 [foo bar 111, apple 888] 5 2 [apple 888]
内容的提问来源于stack exchange,提问作者Bill Fraz
相关产品推荐
相关产品推荐

