检查pandas索引中的元素集

时间:2015-07-17 14:04:58

标签: python pandas

Apparently

'g' in df.index

方式来检查'g'是否在我的索引中。如果我想为许多元素做这件事怎么办?说,我有一个可迭代的对象myIterable(np.ndarray,list),我想得到索引中或不在索引中的元素......

inIterable = [x for x in myIterable if x in df.index]
notInIterable = [x for x in myIterable if x not in df.index]

会起作用,但效率很低。创建innotIn的最有效方法是什么?

2 个答案:

答案 0 :(得分:3)

好的,如果我理解正确测试会员资格,您可以使用intersection

In [132]:

l=[1,2,7]
df = pd.DataFrame({'a':[0,1,2,3,4]})
df.index.intersection(l)
Out[132]:
Int64Index([1, 2], dtype='int64')

对于反向,一种方法是构造一个pandas索引并使用difference

In [137]:

pd.Index(l).difference(df.index)
Out[137]:
Int64Index([7], dtype='int64')

答案 1 :(得分:1)

使用过滤器:

a = [1,2,3,4,5]    # Index
b = [99,2,99,5]    # MyIterable

in = filter(lambda x: x in a, b)

注意:您的示例应为:

in = [x for x in myIterable if x in df.index]

“in”是一个保留字。