0

Say I have a dataframe like this:

enter image description here

I know I can drop levels so that I have columns: ['Season', 'Players', 'Teams']. Is there a function in pandas where I can collapse 'First team' name into a column so that the entire column says 'First team'?

Scott Boston
  • 147,308
  • 15
  • 139
  • 187

1 Answers1

5

IIUC, you can do a few different things, here are two ways:

Where dummy dataframe,

df = pd.DataFrame(np.random.randint(0,100,(5,3)),
                 columns = pd.MultiIndex.from_tuples([('Season', 'Season'), 
                                                      ('First team', 'Players'), 
                                                      ('First team', 'Teams')]))

Input dummy dataframe:

  Season First team      
  Season    Players Teams
0     28         41    53
1     62         87    87
2     43         94     4
3     23         12    93
4     14         43    62

Then use droplevel:

df = df.droplevel(0, axis=1)

Output:

   Season  Players  Teams
0      54       94     19
1      54       47     91
2      56       35     40
3      37       68     14
4      17       78     68

Or flatten multiindex column header using list comprehension:

df.columns = [f'{i}_{j}' for i, j in df.columns]
#Also, can use df.columns = df.columns.map('_'.join)
df

Output:

   Season_Season  First team_Players  First team_Teams
0             54                  94                19
1             54                  47                91
2             56                  35                40
3             37                  68                14
4             17                  78                68
Scott Boston
  • 147,308
  • 15
  • 139
  • 187