DataSwede
DataSwede

Reputation: 5591

Renaming single column of multi-index pandas column

I have a dataframe with a multiindex. The columns look like:

Ex. Df:

      index date        Text        Text        Text        Text        Text
OtherText               OtherText1  OtherText1  OtherText1  OtherText1  OtherText1
Col                     Col1        Col2        Col3        Col4        Col5
        0   17-Jun-14   1           2           3           4           5

Code to create:

arrays = [['Date', 'Text', 'Text', 'Text', 'Text', 'Text'],
      ['', 'OtherText1', 'OtherText1', 'OtherText1', 'OtherText1', 'OtherText1'],
      ['', 'Col1', 'Col2', 'Col3', 'Col4', 'Col5']]
df = pd.DataFrame(randn(1,6), columns=arrays)

Column Names:

[('date', '', ''),
 ('text', 'somemoretext', 'Col1'),
 ('text', 'somemoretext', 'Col2'),
 ('text', 'somemoretext', 'Col3')...]

I'm looking to either rename, or swap the level of the first column. This did not produce an error, but also did not change the columns.

df.rename(columns={"('date', '', '')" : "('', '' 'date')"}, inplace=True)

How do you reorder and/or rename a specific column in a multiindex?

Desired Output:

      index             Text        Text        Text        Text        Text
OtherText               OtherText1  OtherText1  OtherText1  OtherText1  OtherText1
Col          date       Col1        Col2        Col3        Col4        Col5
        0   17-Jun-14   1           2           3           4           5

Upvotes: 2

Views: 1087

Answers (1)

Jeff
Jeff

Reputation: 128948

You can do this.

In [17]: df.set_index('Date').reset_index(col_level=2)
Out[17]: 
                   Text                                        
             OtherText1                                        
       Date        Col1      Col2      Col3      Col4      Col5
0 -1.468055   -1.528279 -1.230268  0.010953 -1.344443  0.650798

I am not sure why you are using multi-indexed columns in this way. HTH.

Upvotes: 2

Related Questions