[英]How to pivot column index to row index in pandas?
I have a pandas dataframe that looks like this:我有一个如下所示的 Pandas 数据框:
A B
Date a b c a b c
20180101 1 1 1 365 365 365
20180102 2 2 2 364 364 364
... ... ... ... ... ... ...
20181231 365 365 365 1 1 1
You can see I have a multilevel column index.你可以看到我有一个多级列索引。 However, I want to transform it into the following format:
但是,我想将其转换为以下格式:
a b c
Date Catelog1
20180101 A 1 1 1
B 365 365 365
20180102 A 2 2 2
B 364 364 364
... ... ... ... ...
20181231 A 365 365 365
B 1 1 1
However this is not obvious to me that how we can achieve this, moreover, what if I have more than two levels on the column axis and I only want to keep the one at the bottom and move all the above indexes on the row axis?然而,这对我来说并不明显,我们如何实现这一点,此外,如果我在列轴上有两个以上的级别并且我只想将一个级别保留在底部并在行轴上移动上述所有索引怎么办?
Setup设置
idx = pd.MultiIndex.from_product([list('AB'), list('abc')])
df = pd.DataFrame(0, columns=idx, index=list('pqrs'))
df
A B
a b c a b c
p 0 0 0 0 0 0
q 0 0 0 0 0 0
r 0 0 0 0 0 0
s 0 0 0 0 0 0
Use swaplevel
and stack
:使用
swaplevel
和stack
:
df.swaplevel(0, 1, axis=1).stack()
a b c
p A 0 0 0
B 0 0 0
q A 0 0 0
B 0 0 0
r A 0 0 0
B 0 0 0
s A 0 0 0
B 0 0 0
Another alternative is stack
with parameter level=0
:另一种选择是参数
level=0
stack
:
df.stack(level=0)
a b c
p A 0 0 0
B 0 0 0
q A 0 0 0
B 0 0 0
r A 0 0 0
B 0 0 0
s A 0 0 0
B 0 0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.