pandas 如何从多索引数据框中删除级别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17084579/
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-09 00:10:15  来源:igfitidea点击:

How to remove levels from a multi-indexed dataframe?

pandasdataframemulti-index

提问by Yariv

For example, I have:

例如,我有:

In [1]: df = pd.DataFrame([8, 9],
                          index=pd.MultiIndex.from_tuples([(1, 1, 1),
                                                           (1, 3, 2)]),
                          columns=['A'])

In [2] df
Out[2]: 
       A
1 1 1  8
  3 2  9

Is there a better way to remove the last level from the index than this:

有没有比这更好的方法从索引中删除最后一个级别:

In [3]: pd.DataFrame(df.values,
                     index=df.index.droplevel(2),
                     columns=df.columns)
Out[3]: 
     A
1 1  8
  3  9

回答by Yariv

df.reset_index(level=2, drop=True)
Out[29]: 
     A
1 1  8
  3  9

回答by Andy Hayden

You don't need to create a new DataFrame instance! You can modify the index:

您不需要创建新的 DataFrame 实例!您可以修改索引:

df.index = df.index.droplevel(2)
df

     A
1 1  8
  3  9

You can also specify negative indices, for selection from the end:

您还可以指定负索引,以便从最后选择:

df.index = df.index.droplevel(-1)

回答by SHASHANK SHEKHAR

If your index has names like

如果您的索引具有类似的名称

       A
X Y Z
1 1 1  8
  3 2  9

Then you can also remove by specifying the index name

然后你也可以通过指定索引名称来删除

df.index = df.index.droplevel(Z)

df.index = df.index.droplevel(Z)