Advanced cross-section with multi-index in pandas

前端 未结 2 1248
梦如初夏
梦如初夏 2021-01-07 00:59

I have the following dataframe:

lb = [(\'A\',\'a\',1), (\'A\',\'a\',2), (\'A\',\'a\',3), (\'A\',\'b\',1), (\'A\',\'b\',2), (\'A\',\'b\',3), (\'B\',\'a\',1),          


        
2条回答
  •  梦谈多话
    2021-01-07 01:25

    Seems you must not use the xs-function with more than a single key. It might be that there exists a fancier slicing, but I would keep it as simple as possible and produce a partial multiindex object that fits my needs:

    cols = df.columns
    thirdlvl = cols.get_level_values('third')
    
    partialcols = [col for col, third in zip(cols, thirdlvl) if third in [2,3]]
    

    With these columns, you get the partial data frame you want:

    print df[partialcolumns]
    
    first          A                                       B                              
    second         a                   b                   a                   b          
    third          2         3         2         3         2         3         2         3
    0       1.103063  1.036151 -0.018996  1.436792 -0.956119  1.587688  2.262837 -1.059619
    1       0.950664  1.847895 -1.172043  0.752676 -0.091956 -0.431509 -0.653317 -0.545843
    2       0.165655 -0.180710 -1.844222 -0.836338  1.687806 -0.469707 -0.374222  0.132809
    3      -0.275194  0.141292  1.021046 -0.010747  1.725614  0.530589  0.106327  0.138661
    4       0.371840  0.455063 -2.643567  0.406322 -0.717277  0.667969  0.660701 -1.324643
    

    EDIT: The simple piece of code below will also find the right columns, of course

     partialcols = [col for col in cols if col[2] in [2,3]]
    

提交回复
热议问题