Pandas – flatten columns

Question:

After:

  1. aggregating with sum()
  2. grouping by ['country', 'match_id']
  3. creating a mean column with mean(axis=1)

I ended up with this:

                     Gls  Ast  avg_attack 
                     sum  sum 
country    match_id
Argentina  20eb96e2  0.10 0.20 0.15
           18eb43e2  0.20 0.30 0.25
...

Now, how do I flatten my dataframe back to this?

country     match_id Gls  Ast  avg_attack 
Argentina  20eb96e2  0.10 0.20 0.15
Argentina  18eb43e2  0.20 0.30 0.25
Asked By: 8-Bit Borges

||

Answers:

Use pandas.Index.get_level_values to flatten the hierarchical index in columns then pandas.DataFrame.reset_index to reset the multi index in rows.

df.columns = df.columns.get_level_values(0)
out = df.reset_index()

# Output :

print(out)

     Country  match_id  Gls   Ast   avg_attack
0  Argentina  20eb96e2  0.10  0.20        0.15
1  Argentina  18eb43e2  0.20  0.30        0.25
Answered By: abokey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.