pandas 数据框检查索引是否存在于多索引中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48382122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas dataframe check if index exists in a multi index
提问by user77005
I have a pandas Dataframe which has a multiindex created using the columns userid
and itemid
. df looks like this
我有一个 Pandas Dataframe,它有一个使用列userid
和itemid
. df 看起来像这样
0 1 2
userid itemid
007 5000 9 4 3
007 4000 6 7 1
009 3000 1 2 3
I want to check if the index [007, 6000] exists in the dataframe df. How can I do that. If I run the following code there is an error TypeError: unhashable type: 'list'
.
我想检查索引 [007, 6000] 是否存在于数据帧 df 中。我怎样才能做到这一点。如果我运行以下代码,则会出现错误TypeError: unhashable type: 'list'
。
if [007, 6000] in df.index:
print('it works')
回答by cs95
For this -
为了这 -
df
0 1 2
userid itemid
7 5000 9 4 3
4000 6 7 1
9 3000 1 2 3
df.index.values
array([(7, 5000), (7, 4000), (9, 3000)], dtype=object)
You can use df.index.isin
.
您可以使用df.index.isin
.
df.index.isin([(7, 5000)])
array([ True, False, False], dtype=bool)
This gives you a mask corresponding to wherethat value can be found. If you just want to know whether it exists or not, use np.ndarray.any
in conjunction with isin
.
这为您提供了一个与可以找到该值的位置相对应的掩码。如果您只想知道它是否存在np.ndarray.any
,请结合使用isin
。
df.index.isin([(7, 5000)]).any()
True
df.index.isin([(7, 6000)]).any()
False