본문 바로가기
개발/Python

[파이썬] XML 파일을 pandas 데이터 프레임으로 변환하는 방법

by MinorMan 2023. 8. 12.
반응형

<질문>

XML 파일을 읽고 pandas DataFrame으로 변환하고 싶습니다.

key                                         type     language    feature            web                         data
e95324a9a6c790ecb95e46cf15bE232ee517651      XXX        EN          xx      www.foo_bar_exmaple.com     A large text with lots of strings and punctuations symbols [...]
bc360cfbafc39970587547215162f0db             XXX        EN          xx      www.foo_bar_exmaple.com     A large text with lots of strings and punctuations symbols [...]
19e71144c50a8b9160b3cvdf2324f0955e906fce     XXX        EN          xx      www.foo_bar_exmaple.com     A large text with lots of strings and punctuations symbols [...]
21d4af9021a174f61b8erf284606c74d9e42         XXX        EN          xx      www.foo_bar_exmaple.com     A large text with lots of strings and punctuations symbols [...]

이것은 내가 이미 시도한 것이지만 몇 가지 오류가 발생하고 아마도 이 작업을 수행하는 더 효율적인 방법이 있을 것입니다.

from lxml import objectify
import pandas as pd

path = 'file_path'
xml = objectify.parse(open(path))
root = xml.getroot()
root.getchildren()[0].getchildren()
df = pd.DataFrame(columns=('key','type', 'language', 'feature', 'web', 'data'))

for i in range(0,len(xml)):
    obj = root.getchildren()[i].getchildren()
    row = dict(zip(['key','type', 'language', 'feature', 'web', 'data'], [obj[0].text, obj[1].text]))
    row_s = pd.Series(row)
    row_s.name = i
    df = df.append(row_s)

누구든지 이 문제에 대해 더 나은 접근 방식을 제공할 수 있습니까?


<답변1>

당신은 쉽게 사용할 수 있습니다xml(Python 표준 라이브러리에서)pandas.DataFrame. 내가 할 일은 다음과 같습니다(파일 바꾸기에서 읽을 때xml_data파일 또는 파일 객체의 이름으로):

import pandas as pd
import xml.etree.ElementTree as ET
import io

def iter_docs(author):
    author_attr = author.attrib
    for doc in author.iter('document'):
        doc_dict = author_attr.copy()
        doc_dict.update(doc.attrib)
        doc_dict['data'] = doc.text
        yield doc_dict

xml_data = io.StringIO(u'''YOUR XML STRING HERE''')

etree = ET.parse(xml_data) #create an ElementTree object 
doc_df = pd.DataFrame(list(iter_docs(etree.getroot())))

원본 문서에 작성자가 여러 명이거나 XML의 루트가author, 다음 생성기를 추가합니다.

def iter_author(etree):
    for author in etree.iter('author'):
        for row in iter_docs(author):
            yield row

그리고 변화doc_df = pd.DataFrame(list(iter_docs(etree.getroot())))에게doc_df = pd.DataFrame(list(iter_author(etree)))

한번 보세요ElementTreetutorial에서 제공하는xml도서관documentation.


<답변2>

현재v1.3, 다음을 간단히 사용할 수 있습니다.

pandas.read_xml(path_or_file)

<답변3>

다음은 xml을 pandas 데이터 프레임으로 변환하는 또 다른 방법입니다. 예를 들어 문자열에서 xml을 구문 분석했지만 이 논리는 파일 읽기에서도 유효합니다.

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

xml_str = '\n\n\n  \n   200\n  \n\n\n \n \n\n' etree = ET.fromstring(xml_str) dfcols = ['id', 'name'] df = pd.DataFrame(columns=dfcols) for i in etree.iter(tag='data'): df = df.append( pd.Series([i.get('id'), i.get('name')], index=dfcols), ignore_index=True) df.head() 

<답변4>

사용을 권장하기 위해 차임xmltodict도서관. 그것은 귀하의 xml 텍스트를 꽤 잘 처리했으며 거의 백만 개의 레코드가있는 xml 파일을 수집하는 데 사용했습니다.


<답변5>

요소 사전을 만든 다음 데이터 프레임으로 직접 변환하여 변환할 수도 있습니다.

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

# Contents of test.xml
#               

root = ET.parse('test.xml').getroot()

tags = {"tags":[]}
for elem in root:
    tag = {}
    tag["Id"] = elem.attrib['Id']
    tag["TagName"] = elem.attrib['TagName']
    tag["Count"] = elem.attrib['Count']
    tags["tags"]. append(tag)

df_users = pd.DataFrame(tags["tags"])
df_users.head()
728x90

댓글