如何通过交叉匹配将字典数据填充到Pandas DataFrame对应单元格?
字典与CSV表格交叉匹配填充实现
需求说明
现有字典project_components,键为项目名称,值为该项目包含的组件列表;另有Template.csv表格,以组件为行、项目为列。需要完成:遍历字典中的每个项目,检查表格内的组件,若项目包含该组件,则在对应单元格填入X,最终保存为新的CSV文件。
示例数据:
- 字典:
project_components = { 'Project_1': ['component_1', 'component_2', 'component_3', 'component_4'], 'Project_2': ['component_2', 'component_3'], 'Project_3': ['component_3', 'component_4'], 'Project_4': ['component_2'] }
- Template.csv内容:
Component / Project; Project_1; Project_2; Project_3; Project_4;Project_N; component_1; component_2; component_3; component_4; component_N;
解决方案
注意事项
读取CSV时需指定分隔符为;,否则无法正确解析列结构。以下提供两种实现方式:
方式1:使用Pandas向量化操作(推荐,效率更高)
避免逐行循环,利用Pandas的批量处理能力:
import pandas as pd def fill_template(): # 读取CSV,指定分号为分隔符,将组件列设为索引 data = pd.read_csv("Template.csv", sep=';', index_col="Component / Project") # 遍历字典中的项目与对应组件列表 for project, components in project_components.items(): # 检查项目列是否存在于表格中 if project in data.columns: # 给该项目下匹配的组件行赋值'X' data.loc[data.index.isin(components), project] = 'X' # 将空值填充为空白(可选,按需调整) data = data.fillna('') # 保存为新CSV,保留分号分隔符 data.to_csv("Filled_Template.csv", sep=';') fill_template()
方式2:使用iterrows()循环(符合你提到的方法)
适合小数据量场景,逐行处理:
import pandas as pd def fill_template_with_iterrows(): # 读取CSV,指定分号为分隔符 data = pd.read_csv("Template.csv", sep=';') # 遍历表格每一行(索引+行数据) for idx, row in data.iterrows(): component = row["Component / Project"] # 遍历字典中的项目 for project, components in project_components.items(): # 检查项目列存在且当前组件属于该项目 if project in data.columns and component in components: data.at[idx, project] = 'X' # 空值填充为空白 data = data.fillna('') # 保存结果,不保留索引列 data.to_csv("Filled_Template.csv", sep=';', index=False) fill_template_with_iterrows()
关键说明
- 读取和保存CSV时必须指定
sep=';',保证格式与原模板一致。 - 向量化操作(方式1)比
iterrows()(方式2)效率高数倍,数据量大时优先选择。 - 代码加入了列存在性检查,避免因字典中项目未在表格中出现而报错。
内容的提问来源于stack exchange,提问作者macder
相关产品推荐
相关产品推荐

