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

如何将Pandas DataFrame转换为指定格式的XML树形结构?

解决方案:将Pandas DataFrame转换为指定XML格式字符串

直接通过Pandas的行遍历功能,结合字符串格式化即可快速生成目标格式的内容,以下是两种可行实现方式:

方法一:使用apply函数处理每行

import pandas as pd
from io import StringIO

# 构建原始DataFrame
df_str = """
Name        Type     Format
loan1        i       type:num;width:10
loan2        a       type:char;width:2
loan3        i       type:date;width:8;dec:0
"""
df = pd.read_csv(StringIO(df_str.strip()), sep='\s\s+', engine='python')

# 定义转换函数:将单行数据转为<th>标签
def generate_th_tag(row):
    return f'<th name="{row["Name"]}" type="{row["Type"]}" format="{row["Format"]}">{row["Name"]}</th>'

# 批量生成所有标签并拼接成字符串
result = '\n'.join(df.apply(generate_th_tag, axis=1))

# 打印结果
print(result)

# 保存为文件(可选)
with open('output.xml', 'w', encoding='utf-8') as f:
    f.write(result)

方法二:使用iterrows()遍历行(更直观)

# 承接上面的df对象
result = '\n'.join([
    f'<th name="{row.Name}" type="{row.Type}" format="{row.Format}">{row.Name}</th>'
    for _, row in df.iterrows()
])

# 输出或保存文件同方法一

说明

  • 两种方法本质都是遍历DataFrame的每一行,将Name、Type、Format字段填充到XML标签模板中。
  • 最终生成的result就是符合要求的字符串,可直接打印输出,或写入TXT/XML文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:32:46