Python:对于多索引数据帧,如何交换行和一个索引列?
我有一个多索引数据帧,如下所示:Python:对于多索引数据帧,如何交换行和一个索引列?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个多索引数据帧,如下所示: col1 col2 ind1 ind2 A x 3 2 y 2 0 B x 2 4 y 2 3 C x 3 1 y 0 0 x
col1 col2
ind1 ind2
A x 3 2
y 2 0
B x 2 4
y 2 3
C x 3 1
y 0 0
x y
ind1 col
A col1 3 2
col2 2 0
B col1 2 4
col2 2 3
C col1 3 1
col2 0 0
现在我想把ind2(x,y)作为列,col1和col2作为第二级索引,如下所示:
col1 col2
ind1 ind2
A x 3 2
y 2 0
B x 2 4
y 2 3
C x 3 1
y 0 0
x y
ind1 col
A col1 3 2
col2 2 0
B col1 2 4
col2 2 3
C col1 3 1
col2 0 0
我试过几种方法,但都失败了,有什么简单的方法可以实现吗
谢谢 这里有一个简单的方法。由于基本上是用索引替换列的名称,因此可以手动获取列和索引名称,然后切换它们
# grab column and index names
col_names = df.columns.values
idx_names = df.index.levels[1].values
# replace them and then rename the inner index
df.index.set_levels(col_names, level=1, inplace=True)
df.columns = idx_names
df.index.set_names('col', level=1, inplace=True)
x y
ind1 col
A col1 3 2
col2 2 0
B col1 2 4
col2 2 3
C col1 3 1
col2 0 0
尝试
df.stack().unstack('ind2')
这很有效,非常感谢!它实际上并没有给出与您想要的相同的结果数据帧。您是否在生成的数据帧数据中出错?不,没有,但我在执行df.stack()之后重新定义了索引名,然后在生成的数据帧上取消堆栈('ind2')。