簡體   English   中英

Python Pandas:檢查列表中的項目是否在df索引中

[英]Python Pandas: check if items from list is in df index

我有一個數據框:

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'])

我也有一個清單:

fixed_cats = ['d','g','ssa']

我想檢查fixed_cats列表中的項目是否在df索引的底部找到。

這是我失敗的嘗試:

football.loc[football.index[-len(fixed_cats):].isin(fixed_cats)]

由於某種原因,它將返回帶有索引['b','c']的df。

預期產量:

索引為“ g”和“ ssa”的df

首次嘗試看到['b','c']的原因是,從內部isin返回的是[False, True, True]的布爾索引,您將從一開始就將其應用於df,您需要再次將其重新應用到最后3行:

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)

因此,上述布爾索引需要應用到最后3行,而不是整個df,這就是您要做的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM