使用.map和lambda从DataFrame匹配数据时返回Series而非值的问题
问题原因
你用lambda x: product_list[(product_list['Country'] == 'Ireland') & (product_list['EAN Number'] == x)]['Local Product Code']返回的是Series对象——哪怕筛选结果只有一个值,它依然是带索引和名称的Series,而非单个字符串/数值,所以map之后Product列就会显示成Series的描述文本。
解决方案
方案1:修改lambda,提取单个值
在lambda里对筛选后的Series取第一个元素,同时处理无匹配的情况避免报错:
inventory_helper['Product'] = np.where(inventory_helper['Country'] != 'IE', inventory_helper['Country'] + inventory_helper['Product'], inventory_helper['EAN (for IE)'].map(lambda x: product_list[(product_list['Country'] == 'Ireland') & (product_list['EAN Number'] == x)]['Local Product Code'].iloc[0] if not product_list[(product_list['Country'] == 'Ireland') & (product_list['EAN Number'] == x)].empty else np.nan) )
注意:这种方式每次map都会遍历整个product_list,数据量大时效率偏低。
方案2:先构建映射字典(高效推荐)
先从product_list提取爱尔兰地区的EAN与编码的映射关系,再用字典做映射:
# 构建爱尔兰地区EAN到Local Product Code的映射字典 ie_product_map = product_list[product_list['Country'] == 'Ireland'].set_index('EAN Number')['Local Product Code'].to_dict() # 执行赋值逻辑 inventory_helper['Product'] = np.where(inventory_helper['Country'] != 'IE', inventory_helper['Country'] + inventory_helper['Product'], inventory_helper['EAN (for IE)'].map(ie_product_map) )
这种方式仅遍历一次product_list,效率更高,且map直接返回单个值;若EAN无匹配,会自动返回NaN,无需额外处理报错。
内容的提问来源于stack exchange,提问作者asuidncsdk
相关产品推荐
相关产品推荐

