Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何用熊猫融化多索引中的第一级列_Python_Pandas - Fatal编程技术网

Python 如何用熊猫融化多索引中的第一级列

Python 如何用熊猫融化多索引中的第一级列,python,pandas,Python,Pandas,我有一个多索引数据帧: df=pd.DataFrame(np.zeros((3,6))) df.columns=pd.MultiIndex.from_arrays([['a','a','b','b','c','c'],[1,2,1,2,1,2]]) df['a']=10 df['b']=20 df['c']=40 print(df) Out[10]: a b c 1 2 1 2 1 2 0 10 10 20 20

我有一个多索引数据帧:

df=pd.DataFrame(np.zeros((3,6)))
df.columns=pd.MultiIndex.from_arrays([['a','a','b','b','c','c'],[1,2,1,2,1,2]])
df['a']=10
df['b']=20
df['c']=40

print(df)

Out[10]: 
    a       b       c    
    1   2   1   2   1   2
0  10  10  20  20  40  40
1  10  10  20  20  40  40
2  10  10  20  20  40  40
我想得到这个:

Out[10]: 

   names  1   2
0      a  10  10
1      a  10  10
2      a  10  10
0      b  20  20
1      b  20  20
2      b  20  20
0      c  40  40
1      c  40  40
2      c  40  40
我知道我可以在数据帧的第一级分离每一列,然后进行追加,但我正在寻找更好的方法

我曾尝试使用melt命令执行此操作,但总是出现错误

有什么想法吗?

使用:

print(df.unstack()
        .unstack(level=1)
        .reset_index(level=1, drop=True)
        .rename_axis('names')
        .reset_index())
  names   1   2
0     a  10  10
1     a  10  10
2     a  10  10
3     b  20  20
4     b  20  20
5     b  20  20
6     c  40  40
7     c  40  40
8     c  40  40