Filtering multiple items in a multi-index Python Panda dataframe

后端 未结 4 2019
轮回少年
轮回少年 2020-12-13 17:29

I have the following table:

Note: Both NSRCODE and PBL_AWI are index\'s

Note: the % Of area column would be filled out just have not done so yet.

<         


        
4条回答
  •  悲&欢浪女
    2020-12-13 17:47

    Also (from here):

    def filter_by(df, constraints):
        """Filter MultiIndex by sublevels."""
        indexer = [constraints[name] if name in constraints else slice(None)
                   for name in df.index.names]
        return df.loc[tuple(indexer)] if len(df.shape) == 1 else df.loc[tuple(indexer),]
    
    pd.Series.filter_by = filter_by
    pd.DataFrame.filter_by = filter_by
    

    ... to be used as

    df.filter_by({'PBL_AWI' : ['Lake', 'River', 'Upland']})
    

    (untested with Panels and higher dimension elements, but I do expect it to work)

提交回复
热议问题