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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With