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

Python中将DataFrame转换为XML时如何按属性分组?

问题:将Pandas DataFrame按Description分组转换为指定格式的XML

我正尝试在Python中将DataFrame转换为XML,DataFrame数据如下:

LoaderTXNID Description ANUMS   Value Date  Fund
67805499    CA67805499  44554   1/27/2023       NC1_AR
67805499    CA67805499  33002   1/27/2023   NC1_AR
67805499    CA67805499  11504   1/27/2023   NC1_AR
67805501    CA67805501  16704   1/27/2023   NC1_AR
67805501    CA67805501  33002   1/27/2023   NC1_AR
67805501    CA67805501  88504   1/27/2023   NC1_AR
67805503    CA67805503  11504   1/27/2023   NC1_AR
67805503    CA67805503  33002   1/27/2023   NC1_AR
67805503    CA67805503  11504   1/27/2023   NC1_AR
67805503    CA67805503  33002   1/27/2023   NC1_AR
67805505    CA67805505  11504   1/27/2023   NC1_AR
67805505    CA67805505  33002   1/27/2023   NC1_AR
67805505    CA67805505  11504   1/27/2023   NC1_AR
67805505    CA67805505  33002   1/27/2023   NC1_AR

需求:
我希望将其转换为如下格式的XML(同一Description的ANUMS值需放在<Entries>标签下):

<Request xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Transactions>
    <Transaction>
        <Description>CA67805499</Description>
        <Entries>
            <Entry>
                <Anum>44554</Anum>
            </Entry>
            <Entry>
                <Anum>33002</Anum>
            </Entry>
            <Entry>
                <Anum>11504</Anum>
            </Entry>
        </Entries>
    </Transaction>
    <Transaction>
        <Description>CA67805501</Description>
        <Entries>
            <Entry>
                <Anum>16704</Anum>
            </Entry>
            <Entry>
                <Anum>33002</Anum>
            </Entry>
            <Entry>
                <Anum>88504</Anum>
            </Entry>
        </Entries>
    </Transaction>
</Transactions>
</Request>

我编写了如下代码:

df= pd.read_csv('C:\Users\Sddl\Desktop\twoigma.csv')
df.columns = df.columns.str.replace(' ', '_')

with open('outputf.xml', 'w') as myfile: 
  myfile.write(df.to_xml(index=False,row_name='Entry',root_name='Transaction',elem_cols={'ANUMS'},attr_cols={'Description'},pretty_print=True,parser='lxml'))

但得到的结果不符合预期,输出如下:

<?xml version="1.0" encoding="UTF-8"?>

<Transaction>

    
        <Entry Description="CA67805499">
            <ANUMS>33002</ANUMS>
        </Entry>

        <Entry Description="CA67805499">
            <ANUMS>11504</ANUMS>
        </Entry>

        <Entry Description="CA67805499">
            <ANUMS>33002</ANUMS>
        </Entry>

        <Entry Description="CA67805501">
            <ANUMS>16704</ANUMS>
        </Entry>

        <Entry Description="CA67805501">
            <ANUMS>33002</ANUMS>
        </Entry>

        <Entry Description="CA67805501">
            <ANUMS>88504</ANUMS>
        </Entry>

</Transaction>      

请问如何在生成XML时对记录进行分组?


解决方案

由于df.to_xml无法直接处理这种嵌套分组的XML结构,需要先对DataFrame分组,再手动构建XML节点:

import pandas as pd
from lxml import etree

# 读取数据并处理列名(注意路径转义)
df = pd.read_csv('C:\\Users\\Sddl\\Desktop\\twoigma.csv')
df.columns = df.columns.str.replace(' ', '_')

# 按Description分组,收集每个分组的ANUMS列表
grouped_data = df.groupby('Description')['ANUMS'].apply(list).reset_index()

# 创建XML根节点及命名空间
root = etree.Element(
    "Request",
    xmlns_xsd="http://www.w3.org/2001/XMLSchema",
    xmlns_xsi="http://www.w3.org/2001/XMLSchema-instance"
)
transactions_node = etree.SubElement(root, "Transactions")

# 遍历分组生成XML结构
for _, row in grouped_data.iterrows():
    # 创建Transaction节点
    transaction_node = etree.SubElement(transactions_node, "Transaction")
    # 添加Description标签
    desc_node = etree.SubElement(transaction_node, "Description")
    desc_node.text = row['Description']
    # 创建Entries节点
    entries_node = etree.SubElement(transaction_node, "Entries")
    # 遍历ANUMS列表生成Entry节点
    for anum in row['ANUMS']:
        entry_node = etree.SubElement(entries_node, "Entry")
        anum_node = etree.SubElement(entry_node, "Anum")
        anum_node.text = str(anum)

# 生成格式化的XML字符串
xml_content = etree.tostring(
    root,
    pretty_print=True,
    encoding='UTF-8',
    xml_declaration=True
).decode('UTF-8')

# 写入文件
with open('outputf.xml', 'w', encoding='UTF-8') as f:
    f.write(xml_content)

关键说明:

  1. 分组处理:用groupby按Description聚合,将同一组的ANUMS整理成列表,为后续嵌套XML结构做准备
  2. 手动构建XML:借助lxml库逐层创建节点,确保Transaction→Entries→Entry的嵌套关系符合需求
  3. 命名空间匹配:在根节点中添加需求指定的XML Schema命名空间
  4. 格式化输出:通过pretty_print=True生成可读性强的缩进XML

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:20:55