Python 基于单个索引创建多索引

Python 基于单个索引创建多索引,python,pandas,Python,Pandas,我有一个Pandas数据框,其中索引类似于: "test1 2011" "test2 2011" "test3 2011" "test1 2012" "test2 2012" "test3 2012" ... 有没有一种简单的方法可以将其转换为多索引 理想输出示例: columns_of_data "2011" "test1" N/A "test2" N/A "test3" N/A "2012" "test1" N/

我有一个Pandas数据框,其中索引类似于:

"test1 2011"
"test2 2011"
"test3 2011"
"test1 2012"
"test2 2012"
"test3 2012"
...
有没有一种简单的方法可以将其转换为多索引

理想输出示例:

                 columns_of_data
"2011" "test1"   N/A
       "test2"   N/A
       "test3"   N/A
"2012" "test1"   N/A
       "test2"   N/A
       "test3"   N/A

如果您有此索引:

idx = ["test1 2011",
"test2 2011",
"test3 2011",
"test1 2012",
"test2 2012",
"test3 2012"]

idx = pd.Index(idx)
然后,您可以拆分每个索引值并将其馈送到
多索引。从_tuples
[:-1]
将按照您所需的输出颠倒“test1”和“2013”的顺序):

例如,这给出了这样一个数据帧:

In [12]: pd.DataFrame(np.random.randn(6,2), index=midx)
Out[12]:
                   0         1
2011 test1  0.340850  2.295460
     test2  1.201304 -0.546234
     test3 -0.667596  1.114521
2012 test1 -0.116098 -0.494520
     test2  0.663173 -0.834933
     test3  0.709935 -0.195774

如果您有此索引:

idx = ["test1 2011",
"test2 2011",
"test3 2011",
"test1 2012",
"test2 2012",
"test3 2012"]

idx = pd.Index(idx)
然后,您可以拆分每个索引值并将其馈送到
多索引。从_tuples
[:-1]
将按照您所需的输出颠倒“test1”和“2013”的顺序):

例如,这给出了这样一个数据帧:

In [12]: pd.DataFrame(np.random.randn(6,2), index=midx)
Out[12]:
                   0         1
2011 test1  0.340850  2.295460
     test2  1.201304 -0.546234
     test3 -0.667596  1.114521
2012 test1 -0.116098 -0.494520
     test2  0.663173 -0.834933
     test3  0.709935 -0.195774

你能给出一个期望结果的例子吗?@greole添加了示例输出你能给出一个期望结果的例子吗?@greole添加了示例输出