我想将XML文件中的数据解析为多索引pandas数据帧。我的XML文件如下所示:
<?xml version="1.0"?>
<catalog>
<book name="Documents/Books/German">
<author>Kerstin Gier</author>
<title>Rubinrot</title>
</book>
<book name="Documents/Articles/English">
<author>Kim Ralls</author>
<title>Midnight Rain</title>
</book>
<book name="Documents/Books/English">
<author>Eva Corets</author>
<title>Maeve Ascendant</title>
</book>
<book name="Documents/Books/English">
<author>Karl Parker</author>
<title>Worldeater</title>
</book>
</catalog>我们的目标是将来自所有图书标签的数据存储到一个多索引pandas数据帧中,该数据帧应如下所示:
author title
Documents Books German Kerstin Gier Rubinrot
English Eva Corets Maeve Ascendant
Karl Parker Worldeater
Articles German Null Null
English Kim Ralls Midnight Rain多索引数据帧的索引应该是属性name包含的路径。我不想硬编码任何路径,因为我的真实示例有许多不同的路径,并且多索引数据帧将具有5-6维。
到目前为止,我的方法是:我开始创建一个索引数据帧,如下所示
path author title
Documents/Books/German Kerstin Gier Rubinrot
Documents/Articles/English Kim Ralls Midnight Rain
Documents/Books/English Eva Corets Maeve Ascendant
Documents/Books/English Karl Parker Worldeater问题是:如何将数据帧转换为以路径结构为索引的多索引数据帧?我看到的问题是在不松开与数据的绑定的情况下更改索引。
发布于 2019-03-28 00:23:17
基于你最初的问题和编辑,下面是后续的解决方案。使用来自here的解析和来自here的思想
我们使用现有的path列,在/上将其拆分,并将其转换为列表,然后使用这些列表值创建新列。
然后我们使用这些列作为新的索引。
df
path author title
0 Documents/Books/German Kerstin_Gier Rubinrot
1 Documents/Articles/English Kim_Ralls Midnight_Rain
2 Documents/Books/English Eva_Corets Maeve_Ascendant
3 Documents/Books/English Karl_Parker Worldeater
df[['cat','type','lang']]=pd.DataFrame(df['path'].str.split('/').values.tolist(), index=df.index)
df
path author title cat type lang
0 Documents/Books/German Kerstin_Gier Rubinrot Documents Books German
1 Documents/Articles/English Kim_Ralls Midnight_Rain Documents Articles English
2 Documents/Books/English Eva_Corets Maeve_Ascendant Documents Books English
3 Documents/Books/English Karl_Parker Worldeater Documents Books English
df.set_index(['cat','type','lang'])
path author title
cat type lang
Documents Books German Documents/Books/German Kerstin_Gier Rubinrot
Articles English Documents/Articles/English Kim_Ralls Midnight_Rain
Books English Documents/Books/English Eva_Corets Maeve_Ascendant
English Documents/Books/English Karl_Parker Worldeater如果需要,显然可以从那里对路径执行drop操作
https://stackoverflow.com/questions/55365328
复制相似问题