python - Pandas dataframe with multiindex column - merge levels -



python - Pandas dataframe with multiindex column - merge levels -

i have dataframe, grouped, multiindex columns below:

import pandas pd codes = ["one","two","three"]; colours = ["black", "white"]; textures = ["soft", "hard"]; n= 100 # length of dataframe df = pd.dataframe({ 'id' : range(1,n+1), 'weeks_elapsed' : [random.choice(range(1,25)) in range(1,n+1)], 'code' : [random.choice(codes) in range(1,n+1)], 'colour': [random.choice(colours) in range(1,n+1)], 'texture': [random.choice(textures) in range(1,n+1)], 'size': [random.randint(1,100) in range(1,n+1)], 'scaled_size': [random.randint(100,1000) in range(1,n+1)] }, columns= ['id', 'weeks_elapsed', 'code','colour', 'texture', 'size', 'scaled_size']) grouped = df.groupby(['code', 'colour']).agg( {'size': [np.sum, np.average, np.size, pd.series.idxmax],'scaled_size': [np.sum, np.average, np.size, pd.series.idxmax]}).reset_index() >> grouped code colour size scaled_size sum average size idxmax sum average size idxmax 0 1 black 1031 60.647059 17 81 185.153944 10.891408 17 47 1 1 white 481 37.000000 13 53 204.139249 15.703019 13 53 2 3 black 822 48.352941 17 6 123.269405 7.251141 17 31 3 3 white 1614 57.642857 28 50 285.638337 10.201369 28 37 4 2 black 523 58.111111 9 85 80.908912 8.989879 9 88 5 2 white 669 41.812500 16 78 82.098870 5.131179 16 78 [6 rows x 10 columns]

how can flatten/merge column index levels as: "level1|level2", e.g. size|sum, scaled_size|sum. etc? if not possible, there way groupby() did above without creating multi-index columns?

you alter columns:

grouped.columns = ['%s%s' % (a, '|%s' % b if b else '') a, b in grouped.columns]

python pandas multi-index

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -