You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含统一cell标签的XML导入Python DataFrame并拆分列

解决XML导入DataFrame时列拆分问题

要正确将这个XML导入Pandas DataFrame,关键是区分元数据行、表头行和数据行,再分别提取表头与对应数据:

步骤说明

  1. 解析XML,提取所有<row>元素
  2. 跳过前4行元数据(pivotlink_gl、发送时间等)
  3. 第5行作为表头,为空<cell>标签生成带序号的列名避免重复
  4. 从第6行开始提取数据,将每个<cell>内容对应到表头列

完整代码

import pandas as pd
import xml.etree.ElementTree as ET

# 替换为你的XML文件路径
xml_file_path = "your_data.xml"
tree = ET.parse(xml_file_path)
root = tree.getroot()

# 获取所有行元素
all_rows = root.findall("row")

# 拆分表头和数据行
header_row = all_rows[4]
data_rows = all_rows[5:]

# 生成列名:为空单元格命名为Unnamed_序号
column_names = []
for idx, cell in enumerate(header_row.findall("cell")):
    cell_text = cell.text.strip() if cell.text else ""
    column_names.append(cell_text if cell_text else f"Unnamed_{idx+1}")

# 提取数据行内容,空单元格转为None(自动转为NaN)
data = []
for row in data_rows:
    row_values = [cell.text.strip() if cell.text else None for cell in row.findall("cell")]
    data.append(row_values)

# 创建DataFrame
df = pd.DataFrame(data, columns=column_names)

# 可选:转换数据类型
# 数值列转换
numeric_cols = ["Credits", "Debits", "Company Currency Amount"]
df[numeric_cols] = df[numeric_cols].apply(pd.to_numeric, errors="coerce")

# 日期列转换
date_cols = ["Posting Date", "Created On"]
df[date_cols] = df[date_cols].apply(pd.to_datetime, format="%m/%d/%Y", errors="coerce")

# 时间列转换
df["Creation Time (UTC)"] = pd.to_datetime(df["Creation Time (UTC)"], format="%H:%M:%S", errors="coerce").dt.time

# 查看结果
print(df.head())

代码解释

  • XML解析:用xml.etree.ElementTree读取XML文件,提取所有行元素
  • 表头处理:遍历表头行的每个<cell>,为空单元格生成唯一列名,避免重复列名报错
  • 数据提取:遍历数据行,将<cell>内容转为字符串或None,空单元格后续自动转为NaN
  • 类型转换:将数值、日期、时间列转为对应数据类型,方便后续分析

处理后,XML中的数据会按表头正确拆分到各列,不会出现所有数据挤在一列的情况。

内容的提问来源于stack exchange,提问作者Curtis Wiser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 16:54:54