create multiindex from dataframe pandas

user5421875 picture user5421875 · Oct 15, 2015 · Viewed 11.1k times · Source

I'm trying to create the multi-index dataframe from following dataframe:

               date_time                   session
              2015-07-30 10:32:54.000        1
              2015-07-30 10:32:54.000        1
              2015-07-30 10:36:39.000        1            
              2015-07-30 10:36:39.000        1
             ........................        1
              2015-07-30 11:58:57.000        2
              2015-07-30 12:18:37.000        2
              2015-07-30 12:28:51.000        2

to obtain smth like:

        date_time                   session
      2015-07-30 10:32:54.000        1
      2015-07-30 10:32:54.000        
      2015-07-30 10:36:39.000                   
      2015-07-30 10:36:39.000        
     ........................        
      2015-07-30 11:58:57.000        2
      2015-07-30 12:18:37.000        
      2015-07-30 12:28:51.000        
      .......................        3

guiding by the answers for this question: MultiIndex Group By in Pandas Data Frame

I tried this code for my data:

def create_multi():
    multi=df.set_index(['session', 'date'], inplace=True)
    print multi

but it returns None I don't know if this method is appropriate for what I need to do and I just use it not correctly, or I should use another method

Answer

EdChum picture EdChum · Oct 15, 2015

You passed inplace=True so it's performed inplace surprisingly enough so returns nothing when you assigned to multi.

def create_multi():
    multi=df.set_index(['session', 'date'], inplace=False)
    print multi

The above would work, check the docs, note that the default is inplace=False so it's strictly not necessary to specify if you want that behaviour