8

Is there a reset_index equivalent for the column headings? In other words, if the column names are an MultiIndex, how would I drop one of the levels?

smci
  • 32,567
  • 20
  • 113
  • 146
Alex Rothberg
  • 10,243
  • 13
  • 60
  • 120
  • 1
    drop a column, or move into the index (as a row)? I don't think there's not really a clean way to move to index aside from wrapping in .T... – Andy Hayden Oct 20 '13 at 07:15
  • The idea being to move a given level of the column names's MultiIndex to the DataFrame as a new row (or optionally just to drop it altogether). – Alex Rothberg Oct 20 '13 at 14:52
  • 1
    Maybe a simpler question is how do I simply drop a level of hierarchy in the column names? – Alex Rothberg Oct 20 '13 at 14:57

3 Answers3

4

Answer to the second question:

df.columns = df.columns.droplevel(level)

First question is as @AndyHayden points out not that straight forward. It only would make sense if your columns names are of the same type as your column values.

joris
  • 133,120
  • 36
  • 247
  • 202
4

Here's a really dumb way to turn your columns into tuples instead:

df.columns = list(df.columns)

You can build on that to get whatever you want, for example if you had a 2 level MultiIndex, to remove the outermost level, you could just do:

df.columns = [col[1] for col in df.columns]

You can't do fancy indexing over the iteration because it's generating tuples, but you can do things like:

df.columns = MultiIndex.from_tuples([col[1:] for col in df.columns])

So you have some options there.

Michel de Ruiter
  • 7,131
  • 5
  • 49
  • 74
Jeff Tratner
  • 16,270
  • 4
  • 47
  • 67
0

Transpose df, reset index, and transopse again.

df.T.reset_index().T

Anton Ovsyannikov
  • 1,010
  • 1
  • 12
  • 30
  • 1
    You actually need `df.T.reset_index(drop=True).T` to prevent the names being reinserted as a regular column. – smci Apr 21 '21 at 20:30
  • Also, for a large dataframe I suspect this uses a lot of memory. Wonder if that can be avoided... – smci Apr 21 '21 at 20:30
  • 1
    As @smci pointed out, you need to drop. And this makes you loose the names of the columns so it breaks the dataframe. – user171780 Oct 26 '21 at 17:05