1

I have an issue with multiindex assignment and will like to store values as highlighted below

I have a function called df_x that is a dataframe and looks like

print df_x

serial    P1       P2       P3

5         21       32       35
10        33       45       76
15        65       99       563 

I will like it to store as follows

For example for level[0] of value alpha

df1 = pd.DataFrame(columns= df_x.columns)

it should create a multiindex on df1 so that

print df1 should look like

print df1


alpha    serial    5     10    15

         P1        21    33    65

         P2        32    45    99

         P3        35    76    563 

However, I am struggling to create multiindex on original df_x dataframe

Any help will be highly appreciated.

1 Answer 1

1

Option 0

pd.concat([df_x], keys=['alpha'])

serial    P1  P2   P3
alpha 5   21  32   35
      10  33  45   76
      15  65  99  563

Option 1

pd.DataFrame(
    df_x.values,
    [['alpha'] * len(df_x), df_x.index],
    df_x.columns
)

serial    P1  P2   P3
alpha 5   21  32   35
      10  33  45   76
      15  65  99  563

Option 2

df_x.set_index(
    pd.MultiIndex.from_product(
        [['alpha'], df_x.index], names=[None, df_x.index.name]
    )
)

Setup

df_x = pd.DataFrame(**{
    'columns': pd.Index(['P1', 'P2', 'P3'], name='serial'),
    'data': [[21, 32, 35], [33, 45, 76], [65, 99, 563]],
    'index': [5, 10, 15]})
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I appreciate that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.