Selecting columns from pandas MultiIndex

前端 未结 7 1058
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 22:36

I have DataFrame with MultiIndex columns that looks like this:

# sample data
col = pd.MultiIndex.from_arrays([[\'one\', \'one\', \'one\', \'two\', \'two\', \         


        
7条回答
  •  被撕碎了的回忆
    2020-11-29 22:54

    You can use either, loc or ix I'll show an example with loc:

    data.loc[:, [('one', 'a'), ('one', 'c'), ('two', 'a'), ('two', 'c')]]
    

    When you have a MultiIndexed DataFrame, and you want to filter out only some of the columns, you have to pass a list of tuples that match those columns. So the itertools approach was pretty much OK, but you don't have to create a new MultiIndex:

    data.loc[:, list(itertools.product(['one', 'two'], ['a', 'c']))]
    

提交回复
热议问题