我有数千个要处理的 XML 文件,它们具有相似的格式,但父级名称和父级数量不同。通过书籍、谷歌、教程和尝试代码,我已经能够提取所有这些数据。参见,例如:Parsing xml to pandas data frame throws memory error and Dynamic search through xml attributes using lxml and xpath in python
然而,我意识到我提取的数据很糟糕,每个父母都重复了一个孩子“时间”。
这是我想要得到的。
Time blah abc
1200 100 2
1300 30 4
1400 70 2
这是我知道如何得到的。但是我当前的方法很笨拙(我将在示例 XML 下方显示)
child Time grandchild
0 blah 1200 100
1 blah 1300 30
...
n-2 abc 1200 2
n-1 abc 1300 4
n abc 1400 2
示例 XML 格式
<outer>
<inner>
<parent name = "blah" id = "1">
<child Time = "1200">
<grandchild>100</grandchild>
</child>
<child Time = "1300">
<grandchild>30</grandchild>
</child>
<child Time = "1400">
<grandchild>70</grandchild>
</child>
</parent>
<parent name = "abc" id = "2">
<child Time = "1200">
<grandchild>2</grandchild>
</child>
<child Time = "1300">
<grandchild>4</grandchild>
</child>
<child Time = "1400">
<grandchild>2</grandchild>
</child>
</parent>
<parent name = "1234" id = "7734">
<other> 12 </other>
</parent>
</inner>
</outer>
这是我如何获得输出的方法:
from lxml import etree, objectify
from pandas import *
dTime=[]
dparent = []
dgrandchild=[]
for df in root.xpath('/*/*/*/parent/child'):
dparent.append(df.getparent().attrib['name'])
## Iterate over attributes of time for specific parent
for attrib in df.attrib:
dTime.append(df.attrib[attrib])
## grandchild is a child of time, and iterate
subfields = df.getchildren()
for subfield in subfields:
dgrandchild.append(subfield.text)
df=DataFrame({'Parent': dparent,'Time':dTime,'grandchild':dgrandchld})
我可以只获取这个输出并重新塑造它,但这似乎效率低下并且是一种非常笨拙的方法。
我想我需要一些味道:
#this does not work
data = []
for elem in root.xpath('/*/*/*/parent/child'):
elem_data = {}
for attrib in elem.attrib:
elem_data['Time'] = elem.attrib[attrib])
for child in elem.getchildren():
elem_data[getparent().attrib['name'])] = child.text
data.append(elem_data)
ndata = DataFrame(data)