XML
In [3]:
!pip install lxml
Requirement already satisfied: lxml in c:\users\ruica\.conda\envs\dl4cv2324\lib\site-packages (5.3.0)
WARNING: Ignoring invalid distribution -otebook (c:\users\ruica\.conda\envs\dl4cv2324\lib\site-packages) WARNING: Ignoring invalid distribution -otebook (c:\users\ruica\.conda\envs\dl4cv2324\lib\site-packages)
In [4]:
# Writing a DataFrame to an XML File
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
df.to_xml('sample.xml', index=False)
In [5]:
# Reading an XML File into a DataFrame
import pandas as pd
df = pd.read_xml('sample.xml')
print(df)
Name Age City 0 Alice 25 New York 1 Bob 30 Los Angeles 2 Charlie 35 Chicago
In [6]:
# Writing a DataFrame to an XML File with Custom Root and Row Tags
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
df.to_xml('sample2.xml', root_name='Persons', row_name='Person', index=False)
In [7]:
# Reading an XML File with Specific XPath
import pandas as pd
df = pd.read_xml('sample2.xml', xpath='.//Person')
print(df)
Name Age City 0 Alice 25 New York 1 Bob 30 Los Angeles 2 Charlie 35 Chicago
In [8]:
# Reading XML with xml.etree.ElementTree
import xml.etree.ElementTree as ET
import pandas as pd
tree = ET.parse('sample2.xml')
root = tree.getroot()
data = []
for record in root.findall('.//Person'):
row = {child.tag: child.text for child in record}
data.append(row)
df = pd.DataFrame(data)
print(df)
Name Age City 0 Alice 25 New York 1 Bob 30 Los Angeles 2 Charlie 35 Chicago
