pandas - 将 XML 文件读取到 Pandas DataFrame

标签 pandas elementtree

这个问题在这里已经有了答案:





How to convert an XML file to nice pandas dataframe?

(5 个回答)


7 个月前关闭。




有人可以帮助将以下 XML 文件转换为 Pandas 数据框:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
	<bathrooms type="dict">
		<n35237 type="number">1.0</n35237>
		<n32238 type="number">3.0</n32238>
		<n44699 type="number">nan</n44699>
	</bathrooms>
	<price type="dict">
		<n35237 type="number">7020000.0</n35237>
		<n32238 type="number">10000000.0</n32238>
		<n44699 type="number">4128000.0</n44699>
	</price>
	<property_id type="dict">
		<n35237 type="number">35237.0</n35237>
		<n32238 type="number">32238.0</n32238>
		<n44699 type="number">44699.0</n44699>
	</property_id>
</root>


它应该是这样的——

OUTPUT

这是我写的代码:-
import pandas as pd
import xml.etree.ElementTree as ET

tree = ET.parse('real_state.xml')
root = tree.getroot()

dfcols = ['property_id', 'price', 'bathrooms']
df_xml = pd.DataFrame(columns=dfcols)

for node in root:
    property_id = node.attrib.get('property_id')
    price = node.attrib.get('price')
    bathrooms = node.attrib.get('bathrooms')

    df_xml = df_xml.append(
            pd.Series([property_id, price, bathrooms], index=dfcols),
            ignore_index=True)


print(df_xml)

我到处都没有,而不是实际值。有人可以告诉它如何修复。谢谢!

最佳答案

如果数据很简单,就像这样,那么您可以执行以下操作:

from lxml import objectify
xml = objectify.parse('Document1.xml')
root = xml.getroot()

bathrooms = [child.text for child in root['bathrooms'].getchildren()]
price = [child.text for child in root['price'].getchildren()]
property_id = [child.text for child in root['property_id'].getchildren()]

data = [bathrooms, price, property_id]
df = pd.DataFrame(data).T
df.columns = ['bathrooms', 'price', 'property_id']

    bathrooms   price      property_id
0   1.0        7020000.0    35237.0
1   3.0        10000000.0   32238.0
2   nan        4128000.0    44699.0

如果它更复杂,那么循环更好。你可以做类似的事情
from lxml import objectify
xml = objectify.parse('Document1.xml')
root = xml.getroot()

data=[]
for i in range(len(root.getchildren())):
    data.append([child.text for child in root.getchildren()[i].getchildren()])

df = pd.DataFrame(data).T
df.columns = ['bathrooms', 'price', 'property_id']

关于pandas - 将 XML 文件读取到 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52968877/

相关文章:

python - 如何在 Python Pandas 中对同一数据框中的两列执行操作?

python - Node.toprettyxml() 在 Python 中向 DOCTYPE 添加换行符

Python 和 ElementTree : return "inner XML" excluding parent element

python - ElementTree模块分离xml内容

python - 使用带有 lxml 前缀的 fromstring()

python - 在Linux桌面上显示实时记分卡

python - 错误 key "axes.prop_cycle"在 matplotlib (Python) 中使用 mplstyle 时出错

python - 删除 Pandas Dataframe 中的重复日期并合并值 - Python

python - 在 Python 中为 .csv 文件中的每条记录保存一个新的 .tsv 文件

python - 如何计算矩阵的协方差?