我在DataFrame
中有pandas
,其中一列是XML字符串。我想要做的是为每个xml节点创建一个列,其列名以规范化形式。例如,
id xmlcolumn
1 <main attr1='abc' attr2='xyz'><item><prop1>text1</prop1><prop2>text2</prop2></item></main>
2 <main ........</main>
我想将其转换为如下数据框:
id main.attr1 main.attr2 main.item.prop1 main.item.prop2
1 abc xyz text1 text2
2 .....
如何保持DataFrame
中的现有列?
答案 0 :(得分:0)
需要做的第一步是将XML字符串转换为pandas Series
(假设在最后总是有相同数量的列)。所以你需要一个像这样的函数:
def convert_xml(raw):
# some etree xml mangling
这可以通过例如在python中使用etree包。返回的系列必须具有索引,其中索引中的每个条目都是要显示的新列名,例如为你的例子:
pd.Series(['abc', 'xyz'], index=['main.attr1', 'main.attr2'])
鉴于此功能,您可以使用pandas执行以下操作(模拟XML修改):
frame = pd.DataFrame({'keep': [42], 'xml': '<foo></foo>'})
temp = frame['xml'].apply(convert_xml)
frame = frame.drop('xml', axis=1)
frame = pd.concat([frame, temp], axis=1)