如何在第二级以下的多索引数据框中删除第一列,排除一些列

时间:2019-12-05 14:44:45

标签: python pandas multi-index

这是我的数据框。我想将级别1中的“ YTD2017”列删除为红色,排除绿色,因为这是我需要的数字。

我知道'drop'函数,并试图将其放入程序中。但是,所有“ YTD2017”都已删除,包括绿色区域。

因此,如何放置红色区域并保持绿色区域。换句话说,有什么办法可以根据我传递的列名删除共济会,而不会影响其他列?

谢谢。

|-----|----------|---------| | Row | EVENT_ID | USER_ID | |-----|----------|---------| | 1 | 1 | 123 | |-----|----------|---------| | 2 | 2 | 321 | |-----|----------|---------|

this is my dataframe structure including sex or seven columns in level 0

1 个答案:

答案 0 :(得分:1)

您可以在Index.isin中指定要删除的值:

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['YTD2017', 'two', 'YTD2017', 'two', 'YTD2017', 'two', 'YTD2017', 'two']]
tuples = list(zip(*arrays))
mux = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])

df = pd.DataFrame(index=[0], columns=mux)
print (df)
first      bar          baz          foo          qux     
second YTD2017  two YTD2017  two YTD2017  two YTD2017  two
0          NaN  NaN     NaN  NaN     NaN  NaN     NaN  NaN

df = (df.loc[:, ~df.columns.get_level_values(0).isin(['foo','qux']) | 
                (df.columns.get_level_values(1) != 'YTD2017')])
print (df)

first      bar          baz       foo  qux
second YTD2017  two YTD2017  two  two  two
0          NaN  NaN     NaN  NaN  NaN  NaN

或为DataFrame.drop创建两个级别的值的元组:

df = df.drop([('foo','YTD2017'), ('qux','YTD2017')], axis=1)