简体   繁体   English

重新组合pandas multiindex列

[英]Regrouping pandas multiindex columns

I am running into an issue where adding new columns to a multiindex column DataFrame causes the new columns to append to the end of the DataFrame. 我遇到了一个问题,在多列索引列DataFrame中添加新列会导致新列附加到DataFrame的末尾。 Eg: 例如:

Group 1         | Group 2        | Group 1 | Group 2 |
------------------------------------------------------
Sub 1  | Sub 2  | Sub 1  | Sub 2 | New Sub | New Sub |

Whereas what I want is: 而我想要的是:

Group 1                   | Group 2                  |
------------------------------------------------------
Sub 1  | Sub 2  | New Sub | Sub 1  | Sub 2 | New Sub |

Is there a way to re-group/order my multiindex to do this? 有没有办法重新分组/订购我的多索引来做到这一点? Note- I do not want to re-order the Sub Groups by name, as New Sub needs to go at the end, and alphabetically might not sort correctly. 注意 - 我不想按名称重新排序子组,因为New Sub需要在最后进行,并且按字母顺序可能无法正确排序。

I think you need reindex or reindex_axis by custom list : 我认为您需要自定义list reindexreindex_axis

df1=pd.DataFrame(columns=pd.MultiIndex.from_product((('C','R', 'A'),(1,2))),
                 data=np.arange(6).reshape(1,-1))
df2=pd.DataFrame(columns=pd.MultiIndex.from_tuples((('C','3'),('R',5),('A',4))),
                 data=[[9,9,4]])
df=df1.join(df2)
print (df)
  C     R     A     C  R  A
   1  2  1  2  1  2  3  5  4
0  0  1  2  3  4  5  9  9  4

df1 = df.reindex(columns = ['C','R','A'], level=0)
print (df1)
   C        R        A      
   1  2  3  1  2  5  1  2  4
0  0  1  9  2  3  9  4  5  4

df1 = df.reindex_axis(['C','R','A'], level=0, axis=1)
print (df1)
   C        R        A      
   1  2  3  1  2  5  1  2  4
0  0  1  9  2  3  9  4  5  4

You just have to call df.sort_index after setting : 您只需在设置后调用df.sort_index

df1=pd.DataFrame(columns=pd.MultiIndex.from_product((('a','b'),
(1,2))),data=np.arange(4).reshape(1,-1))
df2=pd.DataFrame(columns=pd.MultiIndex.from_tuples((('a','3'),('b',5))),data=[[9,9]])
df=df1.join(df2)

#    a     b     a  b
#    1  2  1  2  3  5
# 0  0  1  2  3  9  9

df.sort_index(axis=1,inplace=True)

#    a        b      
#    1  2  3  1  2  5
# 0  0  1  9  2  3  9

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

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