1

Assume a simple dataframe like:

df = pd.DataFrame({'A' : [1], 'B' : [0], 'value1' : [33], 'value2' : [23]})

df
   A  B  value1  value2
0  1  0      33      23

How can I assign superordinated column names s.t. I get a dataframe like:

             values
   A  B      value1  value2
0  1  0          33      23

This should be somehow possible using multiindexing, but I can't figure out how.

Pay attention to that A and B have no joined heading. Therefore

df.columns = pd.MultiIndex.from_product([['values'], df.columns])

is not enough. Hence it is not a duplicate.

I also tried:

 df[['value1','value2']].columns = pd.MultiIndex.from_product([['values'], df[['value1','value2']].columns])

But unfortunately it does not assign the new column name to the original dataframe.

newandlost
  • 935
  • 2
  • 10
  • 21
  • So for `A, B` is no header? – jezrael Dec 12 '18 at 09:09
  • You just want to add an extra level? – cs95 Dec 12 '18 at 09:09
  • ...so, something like `df.columns = pd.MultiIndex.from_product([['values'], df.columns])`? – cs95 Dec 12 '18 at 09:11
  • @jezrael Did you see my editing? I think it is not a duplicate, please reopen it. – newandlost Dec 12 '18 at 09:40
  • @newandlost - yes, I see. But what you need is not possible, is necessary specify each level, like [this](https://stackoverflow.com/q/53700965/2901002) solution. Another idea is use `df = pd.DataFrame({'A' : [1], 'B' : [0], 'value1' : [33], 'value2' : [23]})` and `df = df.set_index(['A','B'])` and then `df.columns = pd.MultiIndex.from_product([['values'], df.columns])`, but not sure if need it. – jezrael Dec 12 '18 at 09:44

0 Answers0