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'?

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.