Python实现CSV文件Types列与预设标签列表的重复数据比对展示
功能实现说明
- 核心需求:读取CSV数据集提取
Types列后,逐行比对预设labels标签列表,精准输出每行与标签列表的重复匹配项,匹配结果需对应原始行索引 - 原遍历逻辑的匹配失效原因:
Types列的单元格内容为字符串形式的列表文本,并非Python原生列表对象;直接传入集合求交集时,会将字符串拆解为单个字符参与匹配,完全无法识别完整标签
原逻辑存在的缺陷
现有遍历代码:
# 初始编写的筛查逻辑 for i in place_type: print (i) a=set(labels).intersection(i) print(a)
- 未做格式转换,匹配维度错误,无法输出完整标签的匹配结果
- 未绑定原始DataFrame索引,输出无法和数据集行位置一一对应
优化后可直接复用的代码实现
import pandas as pd from ast import literal_eval # 1. 预处理Types列:将字符串格式的列表文本解析为原生Python列表,兼容空值场景 place_type = csv['Types'].apply( lambda cell_content: literal_eval(cell_content) if isinstance(cell_content, str) else [] ) # 2. 预先将labels转为集合结构,将匹配效率从O(n)提升至O(1) label_collection = set(labels) # 3. 逐行遍历完成匹配,绑定原始索引输出结果 for row_idx, type_content in place_type.items(): # 计算两个集合的交集,即同时存在于行内容和预设标签的重复项 matched_items = label_collection.intersection(type_content) # 按可读格式输出 print(f"索引 {row_idx} 的匹配重复项:{list(matched_items)}")
匹配效果对照
基于提供的列内容片段,输出结果符合预期:
- 索引0位置:行内容包含
spa、lodging,匹配输出为['spa', 'lodging'] - 索引2、3、4位置:行内容包含
spa,匹配输出为['spa'] - 索引991、992、994、995位置:行内容包含
tourist_attraction,匹配输出为['tourist_attraction'] - 索引993位置:行内容包含
zoo、tourist_attraction,匹配输出为['zoo', 'tourist_attraction']
本次比对使用的预设labels列表:
labels = ['amusement_park', 'campground', 'park', 'tourist_attraction', 'zoo', 'clothing_store', 'department_store', 'library', 'lodging', 'movie_theater', 'shopping_mall', 'spa', 'bakery' , 'bar', 'cafe', 'convenience_store', 'liquor_store', 'night_club', 'restaurant', 'store', 'art_gallery', 'church', 'hindu_temple', 'mosque', 'museum', 'aquarium', 'synagogue']
内容的提问来源于stack exchange,提问作者JsBoon
相关产品推荐
相关产品推荐

