我有下表:
注意:NSRCODE和PBL_AWI都是索引
注意:%of area列将被填写,但尚未完成.
NSRCODE PBL_AWI Area % Of 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
Run Code Online (Sandbox Code Playgroud)
如何过滤掉"PBL_AWI"索引中的项目?例如,我想保留['Lake','River','Upland']
受到这个答案的启发以及对这个问题缺乏简单的回答,我发现自己写了一些语法糖,让生活更容易通过MultiIndex级别进行过滤.
def _filter_series(x, level_name, filter_by):
"""
Filter a pd.Series or pd.DataFrame x by `filter_by` on the MultiIndex level
`level_name`
Uses `pd.Index.get_level_values()` in the background. `filter_by` is either
a string or an iterable.
"""
if isinstance(x, pd.Series) or isinstance(x, pd.DataFrame):
if type(filter_by) is str:
filter_by = [filter_by]
index = x.index.get_level_values(level_name).isin(filter_by)
return x[index]
else:
print "Not a pandas object"
Run Code Online (Sandbox Code Playgroud)
但是,如果我知道熊猫开发团队(我开始,慢慢地!)已经有一个很好的方法来做到这一点,我只是不知道它是什么!
我对吗?