简体   繁体   English

如何仅基于外部索引转置多级熊猫数据帧

[英]how to transpose multiple level pandas dataframe based only on outer index

the below is my dataframe with two level indexing. 下面是我的数据框架,具有两级索引。 I want 'only' the outer index to be transposed as columns. 我希望“仅”将外部索引转置为列。 My desired output would be 2X2 dataframe instead of a 4X1 dataframe as is the case now. 我想要的输出将是2X2数据帧,而不是现在的4X1数据帧。 Can any of you please help? 你们任何人能帮忙吗?

        0
0    0  232

     1  3453

1    0  443

     1  3241

Given you have the multi index you can use unstack() on level 0. 有了多重索引,您可以在级别0上使用unstack()。

import pandas as pd
import numpy as np

index = pd.MultiIndex.from_tuples([(0,0),(0,1),(1,0),(1,1)])
df = pd.DataFrame([[1],[2],[3],[4]] , index=index, columns=[0])

print df.unstack(level=[0])


   0   
   0  1
0  1  3
1  2  4

One way to do this would be to reset the index and then pivot the table indexing on the level_1 of the index, and using level_0 as the columns and 0 as the values. 一种方法是重置索引,然后在索引的level_1上旋转表索引,并使用level_0作为列,并使用0作为值。 Example - 范例-

df.reset_index().pivot(index='level_1',columns='level_0',values=0)

Demo - 演示-

In [66]: index = pd.MultiIndex.from_tuples([(0,0),(0,1),(1,0),(1,1)])

In [67]: df = pd.DataFrame([[1],[2],[3],[4]] , index=index, columns=[0])

In [68]: df
Out[68]:
     0
0 0  1
  1  2
1 0  3
  1  4

In [69]: df.reset_index().pivot(index='level_1',columns='level_0',values=0)
Out[69]:
level_0  0  1
level_1
0        1  3
1        2  4

Later on, if you want you can set the .name attribute for the index as well as the columns to empty string or whatever you want , if you don't want the level_* there. 以后,如果需要,您可以将index以及columns.name属性设置为空字符串或任何所需的内容,如果您不希望将level_*为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM