按列表中(不在)中的索引值对 Pandas 数据框进行切片 [英] Slice Pandas dataframe by index values that are (not) in a list
本文介绍了按列表中(不在)中的索引值对 Pandas 数据框进行切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 pandas
数据框,df
.
I have a pandas
dataframe, df
.
我想选择 df
中不在列表中的所有索引,黑名单.
I want to select all indices in df
that are not in a list, 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.
有没有更好的方法来做到这一点?
Is there a better way to do this?
推荐答案
使用 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屋!
查看全文