【问题标题】:Extract XML info in a df in Python在 Python 中提取 df 中的 XML 信息
【发布时间】:2022-01-19 14:43:34
【问题描述】:

我有问题。在我的 csv 文件中有 XML 列,如下所示:

ID       Name       Request

4223    Axery          <Type xmlns="http://data" 
                xmlns:i="http://www.rij3.instance"><Person><City> 
                <Nr>5050</Nr><Description>Big</Description> 
                <Date>2012-10-30T00:00:00Z</Date></City><Details><Name>London</Name> 
                <Account>5050</Account><Date>2019-07-07T00:00:00Z</Date>
                <Status>Open</Status></Details><..............[more info]>
            ....
            </Person></Type>




            
4001    Jix     <Type xmlns="http://data" 
                xmlns:i="http://www.rij3.instance"><Person><City> 
                <Nr>5024</Nr><Description>Big</Description> 
                <Date>2012-10-30T00:00:00Z</Date></City><Details><Name>London</Name> 
                <Account>5024</Account><Date>2019-07-07T00:00:00Z</Date>
                <Status>Open</Status></Details><..............[more info]>
                ....
                </Person></Type>

....

4067    AOe     <Type xmlns="http://data" 
                xmlns:i="http://www.rij3.instance"><Person><City> 
                <Nr>5011</Nr><Description>Big</Description> 
                <Date>2012-10-30T00:00:00Z</Date></City><Details><Name>London</Name> 
                <Account>5011</Account><Date>2019-07-07T00:00:00Z</Date>
                <Status>Open</Status></Details><..............[more info]>
                ....
                </Person></Type>

           

我想提取 XML 信息。 我使用 Pandas 读取我的 csv 文件

df = pd.read_csv('my_file.csv', header=0, sep='|', error_bad_lines=False)

我想要一个像这样的最终 df:

**ID     Name   Type  Person City Nr    Description Date ........**

4223    Axery                     5050    Big      2012-10-30T00:00:00Z 

有什么建议吗? 我的想法是只使用 XML 列并“连接”结果。

请求:

<Type xmlns="http://data" 
 xmlns:i="http://www.rij3.instance">
 <Person>
   <City>
     <Nr>5050</Nr>
     <Description>Big</Description>
     <Date>2012-10-30T00:00:00Z</Date>
   </City>
   <Details>
     <Name>London</Name>
     <Account>5050</Account>
     <Date>2019-07-07T00:00:00Z</Date>
     <Status>Open</Status>
   </Details>
 </Person>
</Type>

【问题讨论】:

  • 我编辑了代码的语法、大小写和格式,以改进版主接受的问题。然后你把它回滚到原来的版本,在我看来质量很低。我建议您再次应用修订版 2 中的编辑。

标签: python xml csv


【解决方案1】:

我认为解决方案(不知道 Pandas)是从输入 CSV 迭代行并根据在该行中找到的 XML 创建新列。对我来说,这是一个面向行的过程。我不太了解数据框,但据我所知,它们是面向列的^1

以下是我使用 Python 标准 csv 模块执行此操作的方法。

读取 CSV,收集所有数据

  1. 使用 DictReader 读取输入 CSV,它将一行转换为键值到 CSV 标题中名称的值的字典
  2. 迭代行:
    1. 解析 XML 字段并将处理后的值与新键添加到行的字典中
    2. 从行中删除 XML 字段/键
    3. 将该行附加到我所有新行的列表中

写一个新的 CSV

之后,我将使用 DictWriter 根据我在前面步骤中读取/创建的字段创建一个新的 CSV。

import csv
from xml.etree import ElementTree as ET

# Need this to find your XML elements/nodes by name
ns = {'xmlns': 'http://data'}

new_rows = []

with open('input.csv', newline='') as f:
    reader = csv.DictReader(f)
    
    for row in reader:
        # Parse XML and get City node
        xml_str = row['XML']
        tree = ET.fromstring(xml_str)
        city_node = tree.find('./xmlns:Person/xmlns:City', ns)

        # Get individual City values
        city_nr = city_node.find('xmlns:Nr', ns).text
        city_desc = city_node.find('xmlns:Description', ns).text

        row['City_Nr'] = city_nr
        row['City_Description'] = city_desc

        del(row['XML'])

        new_rows.append(row)


new_fieldnames = new_rows[0].keys()

with open('output.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=new_fieldnames)
    writer.writeheader()
    writer.writerows(new_rows)

我模拟了这个 CSV,input.csv

ID,Name,XML
4223,Axery,"<Type xmlns=""http://data"" 
 xmlns:i=""http://www.rij3.instance"">
 <Person>
   <City>
     <Nr>5050</Nr>
     <Description>Big</Description>
     <Date>2012-10-30T00:00:00Z</Date>
   </City>
   <Details>
     <Name>London</Name>
     <Account>5050</Account>
     <Date>2019-07-07T00:00:00Z</Date>
     <Status>Open</Status>
   </Details>
 </Person>
</Type>
"

当我在上面运行我的脚本时,我得到了 output.csv

ID,Name,City_Nr,City_Description
4223,Axery,5050,Big

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多