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

Pandas调用to_xml导出DataFrame为XML报AttributeError如何解决

问题原因
  • 核心原因是你当前使用的Pandas版本过低:DataFrame.to_xml() 是Pandas 1.3.0版本才正式上线的内置方法,低于该版本的Pandas没有这个方法,因此触发AttributeError。
  • 额外存在两个参数&数据问题:
    1. 你的DataFrame列名带有song|前缀,直接传入attr_cols=['title', 'artist', 'year']无法匹配到对应列
    2. 你期望的输出是子节点格式,而attr_cols参数是用来将列设置为行节点的属性,不符合你的输出需求。
解决方案

方案1:升级Pandas使用内置to_xml方法

  1. 先检查当前Pandas版本,确认是否低于1.3.0:
import pandas as pd
print(pd.__version__)
  1. 升级Pandas到最新版本:
# pip 升级
pip install --upgrade pandas

# conda 升级
conda update pandas
  1. 修正列名后调用to_xml:
# 去除列名的song|前缀
df.columns = df.columns.str.replace('song\|', '', regex=True)

# 生成符合要求的XML内容
xml_result = df.to_xml(
    index=False,
    root_name='top_three',
    row_name='song',
    xml_declaration=True,
    pretty_print=True,
    encoding='UTF-8'
)

# 写入本地文件
with open('top_songs.xml', 'w', encoding='UTF-8') as f:
    f.write(xml_result)

方案2:不升级Pandas,手动生成XML

如果不方便升级Pandas版本,可以用Python内置的xml.etree模块手动生成XML:

import xml.etree.ElementTree as ET
from xml.dom import minidom

# 去除列名前缀
df.columns = df.columns.str.replace('song\|', '', regex=True)

# 构造XML节点
root = ET.Element('top_three')
for _, row in df.iterrows():
    song_node = ET.SubElement(root, 'song')
    for field in ['title', 'artist', 'year']:
        field_node = ET.SubElement(song_node, field)
        field_node.text = str(row[field])

# 格式化输出
raw_xml = ET.tostring(root, encoding='UTF-8')
formatted_xml = minidom.parseString(raw_xml).toprettyxml(indent="    ", encoding='UTF-8').decode('UTF-8')

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:15:04