Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flatten group by columns with correct order

Tags:

pandas

import pandas as pd
import numpy as np
df=pd.DataFrame({"item":['a','a','a','b'],"item1":['b','d',np.nan,'c']})
df_grp=df.groupby("item").agg({'item1' : ['last','count']})
df_grp.columns = df_grp.columns.map('_'.join)
df_grp.reset_index()

This gives me

  item item1_last  item1_count
0    a          d            2
1    b          c            1

What I want

  item last_item1  count_item1
0    a          d            2
1    b          c            1

is there a better way to achieve this?

like image 800
william007 Avatar asked Dec 14 '22 07:12

william007


1 Answers

You can use swaplevel before joining the columns.

df_grp.columns = df_grp.columns.swaplevel().map('_'.join)
#df_grp.columns = df_grp.swaplevel(axis=1).columns.map('_'.join)

df_grp.columns = df_grp.columns.swaplevel().map('_'.join)
print(df_grp.reset_index())

  item last_item1  count_item1
0    a          d            2
1    b          c            1
like image 183
anky Avatar answered Feb 15 '23 13:02

anky