pandas 从数据框熊猫创建多索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33143176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:02:22  来源:igfitidea点击:

create multiindex from dataframe pandas

pythonpandasdataframemulti-index

提问by EdChum

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:

获得 smth 像:

        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

以这个问题的答案为指导: Pandas Data Frame 中的 MultiIndex Group By

I tried this code for my data:

我为我的数据尝试了这个代码:

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

but it returns NoneI 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

但它返回 None我不知道这个方法是否适合我需要做的事情,我只是没有正确使用它,或者我应该使用另一种方法

回答by EdChum

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

您通过了,inplace=True因此它在原地执行得足够令人惊讶,因此当您分配给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=Falseso it's strictly not necessary to specify if you want that behaviour

上面的方法可行,检查文档,注意默认是inplace=False这样的,所以没有必要指定你是否想要这种行为