通过不在列表中的索引值对Pandas数据框进行切片 [英] Slice Pandas dataframe by index values that are not in a list

查看:150
本文介绍了通过不在列表中的索引值对Pandas数据框进行切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个pandas数据帧df.

我想选择blacklist.

现在,我使用列表推导来创建所需的标签以进行切片.

Now, I use list comprehension to create the desired labels to slice.

ix=[i for i in df.index if i not in blacklist]  
df_select=df.loc[ix]

工作正常,但如果我经常需要这样做可能会很笨拙.

Works fine, but may be clumsy if I need to do this often.

有更好的方法吗?

推荐答案

使用 isin 并反转布尔值索引以执行标签选择:

Use isin on the index and invert the boolean index to perform label selection:

In [239]:

df = pd.DataFrame({'a':np.random.randn(5)})
df
Out[239]:
          a
0 -0.548275
1 -0.411741
2 -1.187369
3  1.028967
4 -2.755030
In [240]:

t = [2,4]
df.loc[~df.index.isin(t)]
Out[240]:
          a
0 -0.548275
1 -0.411741
3  1.028967

这篇关于通过不在列表中的索引值对Pandas数据框进行切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆