【发布时间】: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?
-
没关系,我通过添加结束标签来修复它。