我正在尝试创建一个脚本,将嵌套的XML文件转换为Pandas数据帧。我找到了这篇文章https://medium.com/@robertopreste/from-xml-to-pandas-dataframes-9292980b1c1c,它很好地完成了到第二层(父级、子级)的工作,但我不知道如何深入到更深的层次(例如孙级),也不知道如何获取子级的属性(例如“neighbor” -> “name”)。以下是我的XML结构:
我希望得到的结构如下所示:
结构需要尽可能灵活,这样在与不同文件一起使用时只需要进行少量编辑。我将获得具有不同数据结构的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文件,因此希望每次都能进行最少的编辑。谢谢!
fully_flatten
应该是原生的pandas! - lys