0

I need to split DataFrame columns into two and add an additional value to the new column. The twist is that I need to lift the original column names up one level and add two new column names.

Given a DataFrame h:

>>> import pandas as pd
>>> h = pd.DataFrame({'a': [0.6, 0.4, 0.1], 'b': [0.2, 0.4, 0.7]})
>>> h
      a    b
0   0.6  0.2
1   0.4  0.4
2   0.1  0.7

I need to lift the original column names up one level and add two new column names. The result should look like this:

>>> # some stuff...
                    a                  b
    expected received  expected received
0        0.6        1       0.2        1
1        0.4        1       0.4        1
2        0.1        1       0.7        1

I've tried this:

>>> h['a1'] = [1, 1, 1]
>>> h['b1'] = [1, 1, 1]
>>> t = [('f', 'expected'),('f', 'received'), ('g', 'expected'), ('g', 'received')]
>>> h.columns = pd.MultiIndex.from_tuples(t)
>>> h
         f                 g         
  expected received expected received
0      0.6      0.2        1        1
1      0.4      0.4        1        1
2      0.1      0.7        1        1

This just renames the columns but does not align them properly. I think the issue is there's no link between a1 and b1 to the expected and received columns.

How do I lift the original column names up one level and add two new column names?

1 Answer 1

1

I am using concat with keys , then swaplevel

h1=h.copy()
h1[:]=1
pd.concat([h,h1],keys=['expected', 'received'],axis=1).\
    swaplevel(0,1,axis=1).\
      sort_index(level=0,axis=1)
Out[233]: 
         a                 b         
  expected received expected received
0      0.6      1.0      0.2      1.0
1      0.4      1.0      0.4      1.0
2      0.1      1.0      0.7      1.0
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.