0

I have a df with a regular datetime index. I need to add multiple index levels. What's a pythonic way to achieve this?

import numpy as np
import pandas as pd

idx = pd.date_range(start="2020-01-01", end="2020-01-10")
vals = {"values": np.random.randint(low=1, high=100, size=10)}
df = pd.DataFrame(data=vals, index=idx)
df.index.name = "time"

I need to add, for example, two new index levels. They must prepend the current index level "time". The result should look like this.

                              values
L0_name  L1_name  time              
L0 value L1 value 2020-01-01      87
                  2020-01-02      46
                  2020-01-03      19
                  2020-01-04      44
                  2020-01-05      94
                  2020-01-06      58
                  2020-01-07      74
                  2020-01-08      32
                  2020-01-09      64
                  2020-01-10      84

1 Answer 1

2

Create new columns by DataFrame.assign, append to existing index by DataFrame.set_index and then change order of them by DataFrame.reorder_levels:

df1 = (df.assign(L0_name = 'L0 value', L1_name='L1 value')
         .set_index(['L0_name','L1_name'], append=True)
         .reorder_levels([1,2,0]))

Or create new MultiIndex, e.g. by MultiIndex.from_product and overwrite existing index by DataFrame.set_index:

idx = pd.MultiIndex.from_product([['L0 value'],['L1 value'], df.index], 
                                 names=['L0_name','L1_name','time'])

df1 = df.set_index(idx)

print (df1)
                              values
L0_name  L1_name  time              
L0 value L1 value 2020-01-01      84
                  2020-01-02      31
                  2020-01-03       4
                  2020-01-04      49
                  2020-01-05      77
                  2020-01-06      49
                  2020-01-07      15
                  2020-01-08      24
                  2020-01-09      49
                  2020-01-10      62
Sign up to request clarification or add additional context in comments.

Comments

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.