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

问题描述 投票:1回答:1

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

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

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

谢谢。

overall.drop('YTD2017',axis=1,level = 1 ,inplace = True)

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

python pandas multi-index
1个回答
0
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.