1

I have a date frame that looks like this :

d = {'text':['A','B'],'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df

  text col1 col2
0 A    1    3
1 B    2    3

I would like to compute the mean by column and add label 'rate' above of header 'text':

  'mean:'  meanofcol1    meanofcol2
  text      col1          col2
0 A         1             3
1 B         2             3

Thanks for your help

atomi kise
  • 93
  • 10

1 Answers1

3

Select only numeric columns by select_dtypes, count mean and merge with another dictionary:

d = {**df.select_dtypes(np.number).mean().to_dict(), **{'text': 'rate: '}}
print (d)
{'col1': 1.5, 'col2': 3.5, 'text': 'rate: '}

Then create MultiIndex with Index.map with MultiIndex.from_arrays:

df.columns = pd.MultiIndex.from_arrays([df.columns.map(d.get), df.columns])
#alternative
#df.columns = [df.columns.map(d.get), df.columns] 
print (df)
  rate:   1.5  3.5
    text col1 col2
0      A    1    3
1      B    2    4

If all numeric columns without first is possible this alternative - convert text column to index, create MultiIndex and last rename_axis:

df = df.set_index('text')
d = df.select_dtypes(np.number).mean()
print (d)
col1    1.5
col2    3.5
dtype: float64

df.columns = pd.MultiIndex.from_arrays([df.columns.map(d.get), df.columns])
#pandas 0.24.1+
df = df.rename_axis(columns=('rate: ','text'), index=None)
#pandas bellow
#df = df.rename_axis(('rate: ','text'), axis=1).rename_axis(None)
print (df)
rate:   1.5  3.5
text   col1 col2
A         1    3
B         2    4

Also text should be dynamically assigned:

df = df.rename_axis(columns=('rate: ', df.index.name), index=None)
#df = df.rename_axis(('rate: ', df.index.name), axis=1).rename_axis(None)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252