微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python-将层次结构(树状)的XML读取到pandas数据框中,以保留层次结构

我有一个XML文档,其中包含分层的树状结构,请参见下面的示例.

该文档包含多个< Message>标签(为方便起见,我仅复制了其中之一).

每个< Message>本身具有一些关联的数据(ID,状态,优先级).

此外,每个< Message>可以包含一个或多个< Street>子级又具有一些相关数据(< name>,< length>).

此外,每个< Street>可以具有一个或多个< Link>子级又具有自己的相关数据(< id>,<方向>).

XML文档示例:

<?xml version="1.0" encoding="ISO-8859-1"?>
<Root xmlns="someNamespace">
<Messages>
<Message id='12345'>
   <status>Active</status>
   <priority>Low</priority>
   <Area>
    <Streets>
     <Street>
      <name>King Street</name>
      <length>Short</length>
       <Link>
        <id>75838745</id>
        <direction>north</direction>
       </Link>
       <Link>
        <id>168745</id>
        <direction>South</direction>
       </Link>
       <Link>
        <id>975416</id>
        <direction>north</direction>
       </Link>
     </Street>
     <Street>
      <name>Queen Street</name>
      <length>Long</length>
       <Link>
        <id>366248</id>
         <direction>West</direction>
       </Link>
       <Link>
        <id>745812</id>
         <direction>East</direction>
       </Link>
     </Street>
    </Streets>
   </Area>
</Message>
</Messages>
</Root>

用Python解析XML并将相关数据存储在变量中不是问题-例如,我可以使用lxml库并读取整个文档,然后执行一些xpath表达式以获取相关字段,或者逐行读取iterparse方法.

但是,我想将数据放入熊猫数据框中,同时保留其中的层次结构.目标是查询单个消息(例如,通过布尔表达式(例如,如果status == Active,然后获取消息及其所有街道及其街道的链接)),并获取属于特定消息(其街道及其街道)的所有数据’链接).如何最好地做到这一点?

我尝试了不同的方法,但是都遇到了问题.

如果我为每个包含信息的XML行创建一个数据框行,然后在[MessageID,StreetName,LinkID]上设置一个MultiIndex,则会得到其中包含很多NaN的索引(通常不建议这样做),因为MessageID不知道其子级街道和链接呢.此外,我不知道如何通过布尔条件选择某些子数据集,而不是仅获取一些没有子项的单行.

在[MessageID,StreetName,LinkID]上执行GroupBy时,我不知道如何从熊猫GroupBy对象取回(可能是MultiIndex)数据帧,因为这里没有要聚合的内容(没有均值/标准差/总和/无论如何,值应保持不变).

有什么建议可以有效地处理吗?

解决方法:

我终于设法解决了如上所述的问题,这就是方法.

我扩展了上面给出的XML文档,使其包含两个消息而不是一个.这就是有效的Python字符串的样子(当然也可以从文件中加载它):

xmlDocument = '''<?xml version="1.0" encoding="ISO-8859-1"?> \
<Root> \
<Messages> \
<Message id='12345'> \
   <status>Active</status> \
   <priority>Low</priority> \
   <Area> \
    <Streets> \
     <Street> \
      <name>King Street</name> \
      <length>Short</length> \
       <Link> \
        <id>75838745</id> \
        <direction>north</direction> \
       </Link> \
       <Link> \
        <id>168745</id> \
        <direction>South</direction> \
       </Link> \
       <Link> \
        <id>975416</id> \
        <direction>north</direction> \
       </Link> \
     </Street> \
     <Street> \
      <name>Queen Street</name> \
      <length>Long</length> \
       <Link> \
        <id>366248</id> \
         <direction>West</direction> \
       </Link> \
       <Link> \
        <id>745812</id> \
         <direction>East</direction> \
       </Link> \
     </Street> \
    </Streets> \
   </Area> \
</Message> \
<Message id='54321'> \
   <status>Inactive</status> \
   <priority>High</priority> \
   <Area> \
    <Streets> \
     <Street> \
      <name>Princess Street</name> \
      <length>Mid</length> \
       <Link> \
        <id>744154</id> \
        <direction>West</direction> \
       </Link> \
       <Link> \
        <id>632214</id> \
        <direction>South</direction> \
       </Link> \
       <Link> \
        <id>654785</id> \
        <direction>East</direction> \
       </Link> \
     </Street> \
     <Street> \
      <name>Prince Street</name> \
      <length>Very Long</length> \
       <Link> \
        <id>1022444</id> \
         <direction>north</direction> \
       </Link> \
       <Link> \
        <id>4474558</id> \
         <direction>South</direction> \
       </Link> \
     </Street> \
    </Streets> \
   </Area> \
</Message> \
</Messages> \
</Root>'''

为了将分层XML结构解析为一个扁平的pandas数据帧,我使用了Python的ElementTree iterparse方法,该方法提供了类似于SAX的接口,可以逐行遍历XML文档,并在特定XML标签开始或结束时触发事件.

对于每个解析的XML行,给定的信息都存储在字典中.使用三个字典,每个字典以某种方式属于一起(消息,街道,链接),然后将其存储在其自己的数据帧行中.当收集到这样一行的所有信息时,该字典将附加到以适当顺序存储所有行的列表中.

这就是XML解析的样子(有关更多说明,请参见内联注释):

# imports
import xml.etree.ElementTree as ET
import pandas as pd

# initialize parsing from Bytes buffer
from io import BytesIO
xmlDocument = BytesIO(xmlDocument.encode('utf-8'))

# initialize dictionaries storing the information to each type of row
messageRow, streetRow, linkRow = {}, {}, {}

# initialize list that stores the single dataframe rows
listofRows = []

# read the xml file line by line and throw signal when specific tags start or end
for event, element in ET.iterparse(xmlDocument, events=('start', 'end')):

    ##########
    # get all information on the current message and store in the appropriate dictionary
    ##########

    # get current message's id attribute
    if event == 'start' and element.tag == 'Message':
        messageRow = {} # re-initialize the dictionary for the current row
        messageRow['messageId'] = element.get('id')

    # get current message's status
    if event == 'end' and element.tag == 'status':
        messageRow['status'] = element.text

    # get current message's priority
    if event == 'end' and element.tag == 'priority':
        messageRow['priority'] = element.text

    # when no more information on the current message is expected, append it to the list of rows
    if event == 'end' and element.tag == 'priority':
        listofRows.append(messageRow)

    ##########
    # get all information on the current street and store in row dictionary
    ##########

    if event == 'end' and element.tag == 'name':
        streetRow = {} # re-initialize the dictionary for the current street row
        streetRow['streetName'] = element.text

    if event == 'end' and element.tag == 'length':
        streetRow['streetLength'] = element.text

    # when no more information on the current street is expected, append it to the list of rows
    if event == 'end' and element.tag == 'length':

        # link the street to the message it belongs to, then append
        streetRow['messageId'] = messageRow['messageId']
        listofRows.append(streetRow)

    ##########
    # get all information on the current link and store in row dictionary
    ##########

    if event == 'end' and element.tag == 'id':
        linkRow = {} # re-initialize the dictionary for the current link row
        linkRow['linkId'] = element.text

    if event == 'end' and element.tag == 'direction':
        linkRow['direction'] = element.text

    # when no more information on the current link is expected, append it to the list of rows
    if event == 'end' and element.tag == 'direction':

        # link the link to the message it belongs to, then append
        linkRow['messageId'] = messageRow['messageId']
        listofRows.append(linkRow)

现在,listofRows是词典的列表,每个词典在其中存储要放入一个数据帧行中的信息.可以使用此列表作为数据源创建数据框

# create dataframe from list of rows and pass column order (would be random otherwise)
df = pd.DataFrame.from_records(listofRows, columns=['messageId', 'status', 'priority', 'streetName', 'streetLength', 'linkId', 'direction'])
print(df)

并给出“原始”数据框:

   messageId    status priority       streetName streetLength    linkId  \
0      12345    Active      Low              NaN          NaN       NaN   
1      12345       NaN      NaN      King Street        Short       NaN   
2      12345       NaN      NaN              NaN          NaN  75838745   
3      12345       NaN      NaN              NaN          NaN    168745   
4      12345       NaN      NaN              NaN          NaN    975416   
5      12345       NaN      NaN     Queen Street         Long       NaN   
6      12345       NaN      NaN              NaN          NaN    366248   
7      12345       NaN      NaN              NaN          NaN    745812   
8      54321  Inactive     High              NaN          NaN       NaN   
9      54321       NaN      NaN  Princess Street          Mid       NaN   
10     54321       NaN      NaN              NaN          NaN    744154   
11     54321       NaN      NaN              NaN          NaN    632214   
12     54321       NaN      NaN              NaN          NaN    654785   
13     54321       NaN      NaN    Prince Street    Very Long       NaN   
14     54321       NaN      NaN              NaN          NaN   1022444   
15     54321       NaN      NaN              NaN          NaN   4474558   

   direction  
0        NaN  
1        NaN  
2      north  
3      South  
4      north  
5        NaN  
6       West  
7       East  
8        NaN  
9        NaN  
10      West  
11     South  
12      East  
13       NaN  
14     north  
15     South  

现在,我们可以将感兴趣的列(messageId,streetName,linkId)设置为该数据帧上的MultiIndex:

# set the columns of interest as MultiIndex
df = df.set_index(['messageId', 'streetName', 'linkId'])
print(df)

这使:

                                      status priority streetLength direction
messageId streetName      linkId                                            
12345     NaN             NaN         Active      Low          NaN       NaN
          King Street     NaN            NaN      NaN        Short       NaN
          NaN             75838745       NaN      NaN          NaN     north
                          168745         NaN      NaN          NaN     South
                          975416         NaN      NaN          NaN     north
          Queen Street    NaN            NaN      NaN         Long       NaN
          NaN             366248         NaN      NaN          NaN      West
                          745812         NaN      NaN          NaN      East
54321     NaN             NaN       Inactive     High          NaN       NaN
          Princess Street NaN            NaN      NaN          Mid       NaN
          NaN             744154         NaN      NaN          NaN      West
                          632214         NaN      NaN          NaN     South
                          654785         NaN      NaN          NaN      East
          Prince Street   NaN            NaN      NaN    Very Long       NaN
          NaN             1022444        NaN      NaN          NaN     north
                          4474558        NaN      NaN          NaN     South

尽管通常不应该考虑将NaN包含在索引中,但对于此用例,我认为它没有任何问题.

最后,为了获得按其messageId(包括其所有“子级”街道和链接)访问单个消息的预期效果,必须将MultiIndexed数据帧按最外部的索引级别进行分组:

# group by the most outer index
groups = df.groupby(level='messageId')

现在,您可以使用以下方法遍历所有消息(并对其进行任何处理)

# iterate over all groups
for key, group in groups:
    print('key: ' + key)
    print('group:')
    print(group)
    print('\n')

哪个返回

key: 12345
group:
                                 status priority streetLength direction
messageId streetName   linkId                                          
12345     NaN          NaN       Active      Low          NaN       NaN
          King Street  NaN          NaN      NaN        Short       NaN
          NaN          75838745     NaN      NaN          NaN     north
                       168745       NaN      NaN          NaN     South
                       975416       NaN      NaN          NaN     north
          Queen Street NaN          NaN      NaN         Long       NaN
          NaN          366248       NaN      NaN          NaN      West
                       745812       NaN      NaN          NaN      East


key: 54321
group:
                                     status priority streetLength direction
messageId streetName      linkId                                           
54321     NaN             NaN      Inactive     High          NaN       NaN
          Princess Street NaN           NaN      NaN          Mid       NaN
          NaN             744154        NaN      NaN          NaN      West
                          632214        NaN      NaN          NaN     South
                          654785        NaN      NaN          NaN      East
          Prince Street   NaN           NaN      NaN    Very Long       NaN
          NaN             1022444       NaN      NaN          NaN     north
                          4474558       NaN      NaN          NaN     South

或者您可以通过messageId访问特定的消息,返回包含messageId以及其所有专用街道和链接的行:

# get groups by key
print('specific group only:')
print(groups.get_group('54321'))

specific group only:
                                     status priority streetLength direction
messageId streetName      linkId                                           
54321     NaN             NaN      Inactive     High          NaN       NaN
          Princess Street NaN           NaN      NaN          Mid       NaN
          NaN             744154        NaN      NaN          NaN      West
                          632214        NaN      NaN          NaN     South
                          654785        NaN      NaN          NaN      East
          Prince Street   NaN           NaN      NaN    Very Long       NaN
          NaN             1022444       NaN      NaN          NaN     north
                          4474558       NaN      NaN          NaN     South

希望这对某人有所帮助.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐