【问题标题】:XML to Pandas Dataframe conversionXML 到 Pandas 数据框的转换
【发布时间】:2018-08-27 05:31:16
【问题描述】:

XML 文件:

<start>
    <Hit>
         <hits path="xxxxx" id="xx" title="xxx">
         <hits path="aaaaa" id="aa" title="aaa">
    </Hit>
    <Hit>
         <hits path="bbbbb" id="bb" title="bbb">
    </Hit>
    <Hit>
         <hits path="qqqqq" id="qq" title="qqq">
         <hits path="wwwww" id="ww" title="www">
         <hits path="ttttt" id="tt" title="ttt">
    </Hit>
</start>

Python 代码:

import xml.etree.cElementTree as et
tree = et.parse(xml_data)
root = tree.getroot()

for child in root:
    record = child.attrib.values()
    all_records.append(record)
    pd1 = pd.DataFrame(all_records,columns=subchild.attrib.keys())

我有非结构化的 XML 文件。 Hit 元素可以有随机数量的子 hits 元素。
我想列出所有 Hit 元素中的所有第一个 hits 子元素。

答案:
数据框内容:

   path    id    title
0  xxxxx   xx    xxx
1  bbbbb   bb    bbb
2  qqqqq   qq    qqq

就是这样。所有其他项目都应忽略。

record = child.attrib.values()

这行代码从 hits 元素中获取所有值。即总共6个值。我只想要 3 个值,因为只有 3 个 Hit 标记可用。

怎么做?

【问题讨论】:

    标签: xml pandas elementtree


    【解决方案1】:

    我认为需要改变:

    record = child.attrib.values()
    

    到:

    record = child[0].attrib.values()
    

    只选择第一个值。

    列表理解解决方案:

    all_records = [child[0].attrib.values() for child in root ]
    

    如果可能的话,一些空的Hit 元素:

    all_records = []
    for child in root:
        if len(child) > 0:
            record = child[0].attrib.values()
            all_records.append(record)
    

    列表理解解决方案:

    all_records = [child[0].attrib.values() for child in root if len(child) > 0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      相关资源
      最近更新 更多