如何通过字典映射为Pandas DataFrame基于部分字符串匹配新增列
Pandas根据字符串包含关键词映射新增列
问题场景
我们需要在Pandas DataFrame中,根据某列字符串是否包含指定关键词,新增一列映射对应的状态。
精确匹配示例
初始DataFrame:
Food Price 0 apple 1.00 1 banana 2.99 2 carrot 3.50
期望新增列后的结果:
Food Price Sale Status 0 apple 1.00 on sale 1 banana 2.99 not on sale 2 carrot 3.50 on sale next week
当字典键与Food列值精确匹配时,可直接用map方法实现:
my_dict = {'apple':'on sale', 'banana':'not on sale', 'carrot':'on sale next week'} df['Sale Status'] = df['Food'].map(my_dict)
实际需求
但实际场景中,Food列是包含关键词的长字符串:
Food Price 0 some other words apple 1.00 1 other banana text 2.99 2 blah blah carrot 3.50
需要实现:当Food列字符串包含字典键时,自动映射对应的值。
解决方案
方法1:apply+自定义函数(直观易读)
通过自定义函数遍历字典键,判断字符串是否包含关键词,返回对应状态:
import pandas as pd # 定义映射字典 my_dict = {'apple':'on sale', 'banana':'not on sale', 'carrot':'on sale next week'} # 构造实际场景的DataFrame df = pd.DataFrame({ 'Food': ['some other words apple', 'other banana text', 'blah blah carrot'], 'Price': [1.00, 2.99, 3.50] }) # 自定义映射逻辑 def get_sale_status(food_str): for key, status in my_dict.items(): if key in food_str: return status return 'unknown' # 处理无匹配的情况 # 新增列 df['Sale Status'] = df['Food'].apply(get_sale_status)
方法2:numpy.select(向量化,高性能)
利用向量化操作构建条件列表,适合大数据集:
import pandas as pd import numpy as np my_dict = {'apple':'on sale', 'banana':'not on sale', 'carrot':'on sale next week'} df = pd.DataFrame({ 'Food': ['some other words apple', 'other banana text', 'blah blah carrot'], 'Price': [1.00, 2.99, 3.50] }) # 生成匹配条件列表和对应状态值 conditions = [df['Food'].str.contains(key) for key in my_dict.keys()] status_values = list(my_dict.values()) # 批量映射状态 df['Sale Status'] = np.select(conditions, status_values, default='unknown')
方法3:正则表达式替换(灵活匹配)
通过正则匹配关键词,直接替换为对应状态:
import pandas as pd my_dict = {'apple':'on sale', 'banana':'not on sale', 'carrot':'on sale next week'} df = pd.DataFrame({ 'Food': ['some other words apple', 'other banana text', 'blah blah carrot'], 'Price': [1.00, 2.99, 3.50] }) # 构建正则匹配模式(匹配任意字典键) pattern = '|'.join(my_dict.keys()) # 替换匹配到的关键词为对应状态 df['Sale Status'] = df['Food'].str.replace(pattern, lambda x: my_dict[x.group()], regex=True) # 处理无匹配的情况 df['Sale Status'] = df.apply(lambda row: row['Sale Status'] if row['Sale Status'] in my_dict.values() else 'unknown', axis=1)
方法对比
- apply方法:逻辑简单直观,代码易维护,适合小数据集。
- numpy.select方法:向量化操作,执行效率更高,适合处理大规模数据。
- 正则替换方法:灵活支持复杂匹配规则,但需要额外处理无匹配的场景。
内容的提问来源于stack exchange,提问作者PeterK
相关产品推荐
相关产品推荐

