【问题标题】:Python: Extracting XML to DataFrame (Pandas)Python:将 XML 提取到 DataFrame (Pandas)
【发布时间】:2018-11-19 07:35:40
【问题描述】:

有一个如下所示的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<comments>
<row Id="1" PostId="2" Score="0" Text="(...)" CreationDate="2011-08-30T21:15:28.063" UserId="16" />
<row Id="2" PostId="17" Score="1" Text="(...)" CreationDate="2011-08-30T21:24:56.573" UserId="27" />
<row Id="3" PostId="26" Score="0" Text="(...)" UserId="9" />
</comments>

我正在尝试将 ID、Text 和 CreationDate 列提取到 pandas DF 中,我尝试了以下操作:

import xml.etree.cElementTree as et
import pandas as pd
path = '/.../...'
dfcols = ['ID', 'Text', 'CreationDate']
df_xml = pd.DataFrame(columns=dfcols)

root = et.parse(path)
rows = root.findall('.//row')
for row in rows:
    ID = row.find('Id')
    text = row.find('Text')
    date = row.find('CreationDate')
    print(ID, text, date)
    df_xml = df_xml.append(pd.Series([ID, text, date], index=dfcols), ignore_index=True)

print(df_xml)

但是输出是: 无 无 无

您能告诉我如何解决这个问题吗? 谢谢

【问题讨论】:

标签: python xml pandas dataframe


【解决方案1】:

只是代码中的一个小改动

ID = row.get('Id')
text = row.get('Text')
date = row.get('CreationDate')

【讨论】:

    【解决方案2】:

    基于@Parfait 解决方案,我编写了将列作为参数并返回 Pandas DataFrame 的版本。

    test.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <comments>
    <row Id="1" PostId="2" Score="0" Text="(.1.)" CreationDate="2011-08-30T21:15:28.063" UserId="16" />
    <row Id="2" PostId="17" Score="1" Text="(.2.)" CreationDate="2011-08-30T21:24:56.573" UserId="27" />
    <row Id="3" PostId="26" Score="0" Text="(.3.)" UserId="9" />
    </comments>
    

    xml_to_pandas.py:

    '''Xml to Pandas DataFrame Convertor.'''
    
    import xml.etree.cElementTree as et
    import pandas as pd
    
    
    def xml_to_pandas(root, columns, row_name):
      '''get xml.etree root, the columns and return Pandas DataFrame'''
      df = None
      try:
    
        rows = root.findall('.//{}'.format(row_name))
    
        xml_data = [[row.get(c) for c in columns] for row in rows]  # NESTED LIST
    
        df = pd.DataFrame(xml_data, columns=columns)
      except Exception as e:
        print('[xml_to_pandas] Exception: {}.'.format(e))
    
      return df
    
    
    path = 'test.xml'
    row_name = 'row'
    columns = ['ID', 'Text', 'CreationDate']
    
    root = et.parse(path)
    df = xml_to_pandas(root, columns, row_name)
    print(df)
    

    输出:

    【讨论】:

      【解决方案3】:

      正如黄金会员 Python/pandas/numpy 大师 @unutbu 在此 solution 中所建议的那样:

      永远不要在 for 循环中调用 DataFrame.append 或 pd.concat。它会导致二次复制。

      因此,请考虑将您的 XML 数据解析为单独的列表,然后在任何循环之外的一次调用中将列表传递给 DataFrame 构造函数。实际上,您可以将带有列表推导的嵌套列表直接传递给构造函数:

      path = 'AttributesXMLPandas.xml'
      dfcols = ['ID', 'Text', 'CreationDate']
      
      root = et.parse(path)
      rows = root.findall('.//row')
      
      # NESTED LIST
      xml_data = [[row.get('Id'), row.get('Text'), row.get('CreationDate')] 
                  for row in rows]
      
      df_xml = pd.DataFrame(xml_data, columns=dfcols)
      
      print(df_xml)
      
      #   ID   Text             CreationDate
      # 0  1  (...)  2011-08-30T21:15:28.063
      # 1  2  (...)  2011-08-30T21:24:56.573
      # 2  3  (...)                     None
      

      【讨论】:

        猜你喜欢
        • 2019-03-28
        • 1970-01-01
        • 2019-06-20
        • 1970-01-01
        • 1970-01-01
        • 2018-05-18
        • 1970-01-01
        • 2020-07-08
        • 2017-04-29
        相关资源
        最近更新 更多