Reputation: 14112
I have a dataframe:
data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012],
'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions', 'Lions', 'Lions'],
'wins': ['11102', '8425', '12%', '15%', '11%', '6%', '20%', '4%'],
'losses': ['5222', '8888', '6%', '1%', '5%', '30%', '6%', '12%'],
}
football = pd.DataFrame(data, index=['a','b','c','d','e','f','g','ssa'], columns=['year', 'team', 'wins', 'losses'])
I also have a list:
fixed_cats = ['d','g','ssa']
I would like to check if the items from the fixed_cats list are found at the bottom of the df's index.
Here is my failed attempt:
football.loc[football.index[-len(fixed_cats):].isin(fixed_cats)]
for some reason, this returns a df with the index ['b','c'].
Expected output:
a df with the index of 'g' and 'ssa'
Upvotes: 4
Views: 3451
Reputation: 394199
The reason you saw ['b','c']
in your first attempt is that what is returned from the inner isin
is a boolean index of [False, True, True]
which you're applying to the df from the beginning, you need to reapply it again to the last 3 rows:
In [21]:
fixed_cats = ['d','g','ssa']
football[-len(fixed_cats):][football.index[-len(fixed_cats):].isin(fixed_cats)]
Out[21]:
year team wins losses
g 2011 Lions 20% 6%
ssa 2012 Lions 4% 12%
In [22]:
football.index[-len(fixed_cats):].isin(fixed_cats)
Out[22]:
array([False, True, True], dtype=bool)
So the above boolean index needs to be applied to the last 3 rows rather to the entire df again which is what you are doing
Upvotes: 4