【问题标题】:XML to Pandas dataFrame returns NoneXML 到 Pandas 数据帧返回无
【发布时间】:2019-08-07 14:03:46
【问题描述】:

我从数据科学和熊猫开始,我正在尝试使用 XML 信息填充熊猫数据框,这是我的代码:

import xml.etree.cElementTree as et
import pandas as pd
import sys

def getvalueofnode(node):
    """ return node text or None """
    return node.text if node is not None else None


def main():
    parsed_xml = et.parse("test2.xml")
    dfcols = ['Country','Club', 'Founded']
    df_xml = pd.DataFrame(columns=dfcols)

    for node in parsed_xml.getroot():
        Country = node.attrib.get('country')
        Club = node.find('Name')
        Founded = node.find('Founded')

        df_xml = df_xml.append(
            pd.Series([Country, getvalueofnode(Club),getvalueofnode(Founded)], index=dfcols),
            ignore_index=True)

    print(df_xml)

main()

这是我的输出:

乡村俱乐部成立

0 无 无 无

这是我的 XML 文件:

<?xml version="1.0"?>
<SoccerFeed timestamp="20181123T153249+0000">
  <SoccerDocument Type="SQUADS Latest" competition_code="FR_L1" competition_id="24" competition_name="French Ligue 1" season_id="2016" season_name="Season 2016/2017">
    <Team country="France" country_id="8" country_iso="FR" region_id="17" region_name="Europe" >
      <Founded>1919</Founded>
      <Name>Angers</Name>
   <...>
   <Team country="France" country_id="8" country_iso="FR" region_id="17" region_name="Europe" >
      <Founded>1905</Founded>
      <Name>Bastia</Name>

为什么我无法获得包含所需信息的 Panda 数据框?我错过了代码中的某些内容吗?谢谢你的帮助

【问题讨论】:

  • 在尝试使用您的代码解析 XML DOM 时出现错误,您能否分享一个有效的 xml?
  • 没关系,我通过添加结束标签来修复它。

标签: python pandas dataframe


【解决方案1】:

在 XML 中,&lt;Founded&gt;&lt;Name&gt;&lt;Team&gt; 标记的子标记,country 属性也是 &lt;Team&gt; 标记的一部分。因此,我们应该 iterate 覆盖 &lt;Team&gt; 标签的 XML DOM。接下来,应该有一些方法可以在每次迭代中存储for 循环的值,因为这些将是每列的行值。我们可以通过创建一个包含三列的字典(df_dict)并将它们的值设置为空列表来做到这一点。我们在每次迭代中为每个CountryClubFounded 附加相应的列表。最后,我们从这个字典中创建 Dataframe(df)。

import xml.etree.cElementTree as et
import pandas as pd

def main():
    parsed_xml = et.parse("test.xml")
    df_dict = {'Country':[],'Club':[], 'Founded':[]}    
    root = parsed_xml.getroot()
    for country in root.iter('Team'):
        Country = country.attrib.get('country')
        Club = country.find('Name').text
        Founded = country.find('Founded').text 
        df_dict['Country'].append(Country)
        df_dict['Club'].append(Club)
        df_dict['Founded'].append(Founded) 

    print('Dict for dataframe: {}'.format(df_dict))
    df = pd.DataFrame(df_dict)
    print("Dataframe: \n{}".format(df))

main()

以下是运行此脚本的输出:

#Output:
Dict for dataframe: {'Country': ['France', 'France'], 'Club': ['Angers', 'Bastia'], 'Founded': ['1919', '1905']}
Dataframe:
  Country    Club Founded
0  France  Angers    1919
1  France  Bastia    1905

【讨论】:

    猜你喜欢
    • 2013-02-10
    • 2021-10-11
    • 2021-04-22
    • 2020-07-19
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多