本文介绍了从索引交换一级到列级(Pandas Multiindex Dataframe)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个多索引的pandas.Dataframe,就像这样:
I have a multiindexed pandas.Dataframe which is something like this:
BAZ PAL
Foo Bar
124 1 A B
2 C D
134 1 E F
2 G H
我需要以适当的方式将索引的一级交换为列.我需要结束这样的事情:
I need to swap level-one from index with columns in appropriate way. I need to end up with something like this:
124 134
Coo Bar
BAZ 1 A E
2 C G
PAL 1 B F
2 D H
推荐答案
您需要取消堆叠现有的索引级别Foo
,堆叠所需的列'Coo',然后重新排列索引级别.交换索引级别后,您可能希望对其进行排序.最后,您可能要删除所有值的列名(val
).
You need to unstack your existing index level Foo
, stack your desired column 'Coo', and then rearrange the index levels. After swapping your index levels, you probably want to sort it. As a final touch, you may want to drop the column name of all the values (val
).
df = (pd.DataFrame({'Foo': [124, 124, 134, 134] * 2,
'Bar': [1, 2, 1, 2] * 2,
'Coo': ['BAZ'] * 4 + ['PAL'] * 4,
'val': list('ACEGBDFH')})
.set_index(['Foo', 'Bar', 'Coo'])
.unstack('Coo'))
>>> df
val
Coo BAZ PAL
Foo Bar
124 1 A B
2 C D
134 1 E F
2 G H
df = df.unstack('Foo').stack('Coo')
df.index = df.index.swaplevel(0, 1)
>>> df
val
Foo 124 134
Coo Bar
BAZ 1 A E
PAL 1 B F
BAZ 2 C G
PAL 2 D H
df.sort_index(inplace=True)
>>> df
val
Foo 124 134
Coo Bar
BAZ 1 A E
2 C G
PAL 1 B F
2 D H
df.columns = df.columns.droplevel()
>>> df
Foo 124 134
Coo Bar
BAZ 1 A E
2 C G
PAL 1 B F
2 D H
这篇关于从索引交换一级到列级(Pandas Multiindex Dataframe)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!