如何用Python将Excel非结构化数据转结构化表格并批量填充指定列值
Python处理非结构化Excel数据实现结构化转换方案
实现思路
- 维护一个全局变量存储当前读取到的地点名称,遇到新的地点行时更新该变量
- 逐行遍历原始数据,过滤掉地点行、表头行(即包含
# of Cafes to Visit的行) - 识别到有效数据行(前三列均为数值)时,将当前存储的地点填入
Col 4,并将该行加入结果集 - 自动过滤Paris、Rome这类没有对应有效数据的地点,因为没有数据行触发写入逻辑,自然不会出现在结果中
完整代码示例
import pandas as pd # 读取原始Excel数据,替换为你的实际文件路径 df = pd.read_excel("your_file_path.xlsx") current_location = None result_rows = [] for _, row in df.iterrows(): # 识别地点行,更新当前存储的地点 if str(row["Col 1"]).strip() == "Location": current_location = str(row["Col 2"]).strip() continue # 识别表头行,直接跳过 if str(row["Col 2"]).strip() == "# of Cafes to Visit": continue # 验证当前行是否为有效数据行(Col1可转为数值即判定为有效) try: float(row["Col 1"]) # 填充地点到第四列,将该行加入结果集 row["Col 4"] = current_location result_rows.append(row) except ValueError: # 非数值行直接跳过 continue # 转换为结构化DataFrame structured_df = pd.DataFrame(result_rows) # 可选操作:重置索引、导出为新的Excel文件 structured_df = structured_df.reset_index(drop=True) structured_df.to_excel("structured_output.xlsx", index=False)
效果验证
按照你提供的输入样例运行代码后,输出结果和你给出的预期样例完全匹配,所有无效行都会被自动过滤,有效数据行的Col 4会正确填充所属地点。
内容的提问来源于stack exchange,提问作者Nelly Yuki
相关产品推荐
相关产品推荐

