Selecting columns from pandas MultiIndex

前端 未结 7 1046
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  Happy的楠姐
    2020-11-29 22:54

    A slightly easier, to my mind, riff on Marc P.'s answer using slice:

    import pandas as pd
    col = pd.MultiIndex.from_arrays([['one', 'one', 'one', 'two', 'two', 'two'], ['a', 'b', 'c', 'a', 'b', 'c']])
    data = pd.DataFrame(np.random.randn(4, 6), columns=col)
    
    data.loc[:, pd.IndexSlice[:, ['a', 'c']]]
    
            one                 two          
              a         c         a         c
    0 -1.731008  0.718260 -1.088025 -1.489936
    1 -0.681189  1.055909  1.825839  0.149438
    2 -1.674623  0.769062  1.857317  0.756074
    3  0.408313  1.291998  0.833145 -0.471879
    

    As of pandas 0.21 or so, .select is deprecated in favour of .loc.

提交回复
热议问题