python - 在多索引 Python Panda 数据框中过滤多个项目

标签 python filter pandas indexing

我有下表:

NSRCODE  PBL_AWI          Area           
CM       BONS             44705.492941
         BTNN            253854.591990
         FONG             41625.590370
         FONS             16814.159680
         Lake             57124.819333
         River             1603.906642
         SONS            583958.444751
         STNN             45603.837177
         clearcut        106139.013930
         disturbed       127719.865675
         lowland         118795.578059
         upland         2701289.270193
LBH      BFNN            289207.169650
         BONS           9140084.716743
         BTNI             33713.160390
         BTNN          19748004.789040
         FONG           1687122.469691
         FONS           5169959.591270
         FTNI            317251.976160
         FTNN           6536472.869395
         Lake            258046.508310
         River            44262.807900
         SONS           4379097.677405
         burn regen      744773.210860
         clearcut         54066.756790
         disturbed       597561.471686
         lowland       12591619.141842
         upland        23843453.638117

注意:NSRCODEPBL_AWI 都是索引。

如何在 PBL_AWI 列中搜索值?例如,我想保留值 ['Lake', 'River', 'Upland'].

最佳答案

你可以get_level_values结合 bool 切片。

In [50]:

print df[np.in1d(df.index.get_level_values(1), ['Lake', 'River', 'Upland'])]
                          Area
NSRCODE PBL_AWI               
CM      Lake      57124.819333
        River      1603.906642
LBH     Lake     258046.508310
        River     44262.807900

同样的想法可以用很多不同的方式表达,比如df[df.index.get_level_values('PBL_AWI').isin(['Lake', 'River', 'Upland'])]

请注意,您的数据中有 'upland' 而不是 'Upland'

关于python - 在多索引 Python Panda 数据框中过滤多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25224545/

相关文章:

python - 将 pandas DataFrames : how do I apply scipy. stats.sem 分组给他们?

python - 在python3中导入sdl2时出错

python - 在 python 中应用巴特沃斯带通滤波器后,如何去除信号开头的大尖峰?

python - 如何在按某些条件查询后更改 pandas DataFrame 值

python - 在 pandas 数据框(和)列表上使用 scipy pdist

python - 在另一个数组中的位置映射 numpy 数组和求和值

python - Matplotlib 错误会导致内存泄漏。我怎样才能释放那段内存?

scala - 在获得成功结果数后,在列表上结束 Scala 中的过滤器

audio - 按音频功能过滤 Spotify ID

python - Python 中是否有与 tsset 和 tsfill 等效的代码?