【发布时间】:2020-02-12 16:53:03
【问题描述】:
我正在尝试创建一个脚本来将嵌套的 XML 文件转换为 Pandas 数据框。我找到了这篇文章https://medium.com/@robertopreste/from-xml-to-pandas-dataframes-9292980b1c1c,它在进入第二级(父母、孩子)方面做得很好,但我既不知道如何进入更深层次(例如孙子),也不知道如何进入孩子(例如“邻居”->“名字”)。
这是我的 XML 结构:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
<neighbor2 name="Italy" direction="S"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
这是我的代码:
import pandas as pd
import xml.etree.ElementTree as et
def parse_XML(xml_file, df_cols):
xtree = et.parse(xml_file)
xroot = xtree.getroot()
rows = []
for node in xroot:
res = []
res.append(node.attrib.get(df_cols[0]))
for el in df_cols[1:]:
if node is not None and node.find(el) is not None:
res.append(node.find(el).text)
else:
res.append(None)
rows.append({df_cols[i]: res[i]
for i, _ in enumerate(df_cols)})
out_df = pd.DataFrame(rows, columns=df_cols)
return out_df
xml_file= "example.xml"
df_cols = ["name","year","direction"]
out_df=parse_XML(xml_file, df_cols)
out_df
我想要得到的是如下结构:
| name | year | neighbor name 1 | neighbor direction 1 | neighbor2 name 1 |
|---------------|------|-----------------|----------------------|------------------|
| Liechtenstein | 2008 | Austria | E | Italy |
| | | | | |
| | | | | |
结构需要尽可能灵活,以便与不同的文件一起使用时需要很少的编辑。我正在获取具有不同数据结构的 XML 文件,因此我希望每次都能够进行一些最少的编辑。
非常感谢!!
【问题讨论】:
标签: python python-3.x xml pandas