擅长:python、mysql、java
<p>要扩展Viktor的优秀答案(并对其进行一些微调以处理重复的列),可以将其设置为<code>to_xml</code>数据帧方法:</p>
<pre><code>def to_xml(df, filename=None, mode='w'):
def row_to_xml(row):
xml = ['<item>']
for i, col_name in enumerate(row.index):
xml.append(' <field name="{0}">{1}</field>'.format(col_name, row.iloc[i]))
xml.append('</item>')
return '\n'.join(xml)
res = '\n'.join(df.apply(row_to_xml, axis=1))
if filename is None:
return res
with open(filename, mode) as f:
f.write(res)
pd.DataFrame.to_xml = to_xml
</code></pre>
<p>然后可以打印xml:</p>
<pre><code>In [21]: print df.to_xml()
<item>
<field name="field_1">cat</field>
<field name="field_2">15,263</field>
<field name="field_3">2.52</field>
<field name="field_4">00:03:00</field>
</item>
<item>
...
</code></pre>
<p>或将其保存到文件:</p>
<pre><code>In [22]: df.to_xml('foo.xml')
</code></pre>
<p><em>显然,这个示例应该进行调整,以适合您的xml标准。</em></p>