colinfang
colinfang

Reputation: 21707

Pandas: convert a multiindex column headers into normal column header?

My data frame looks like this, with columns header being MultiIndex, (True, False are boolean type).

    date         a            value
id                   False           True
0    2013-11-26  0   346.749819      0.000000
1    2013-11-27  1   1786.449591     21442.388942
2    2013-11-28  1   677837.782372   92998.909207
3    2013-11-29  0   731443.020535   322093.419644
4    2013-11-30  1   18082.124124    11637.523334

How can I easily make it into this:

id   date        a   value: False    value: True
0    2013-11-26  0   346.749819      0.000000
1    2013-11-27  1   1786.449591     21442.388942
2    2013-11-28  1   677837.782372   92998.909207
3    2013-11-29  0   731443.020535   322093.419644
4    2013-11-30  1   18082.124124    11637.523334

The column names are not important, as I can modify them later using rename.

Upvotes: 2

Views: 1928

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

Here is a more pythonic way of flattening those multiindex columns in a dataframe:

df.columns = df.columns.map(' : '.join)

Upvotes: 0

chrisb
chrisb

Reputation: 52236

If names aren't important, you could do this, which will reset the row index, and replace the MultiIndex columns with a tuple with each level.

df = df.reset_index()
df.columns = list(df.columns)

Upvotes: 2

Related Questions