嵌套 XML 到 Pandas 数据框

2023-12-08

我正在尝试创建一个脚本来将嵌套 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 文件,因此我希望每次都能进行一些最少的编辑。

多谢!!


我已经为类似的用例制作了一个包。它也可以在这里工作。

pip install pandas_read_xml

你可以做类似的事情

import pandas_read_xml as pdx

df = pdx.read_xml('filename.xml', ['data'])

要压平,你可以

df = pdx.flatten(df)

or

df = pdx.fully_flatten(df)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

嵌套 XML 到 Pandas 数据框 的相关文章

随机推荐