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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:05:09  来源:igfitidea点击:

pandas dataframe check if index exists in a multi index

pythonpandasdataframemulti-index

提问by user77005

I have a pandas Dataframe which has a multiindex created using the columns useridand itemid. df looks like this

我有一个 Pandas Dataframe,它有一个使用列useriditemid. 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.anyin conjunction with isin.

这为您提供了一个与可以找到该值的位置相对应的掩码。如果您只想知道它是否存在np.ndarray.any,请结合使用isin

df.index.isin([(7, 5000)]).any()
True

df.index.isin([(7, 6000)]).any()
False

回答by jezrael

Use Index.isin:

使用Index.isin

df = df.index.isin([('007','5000')])
print (df)
[ True False False]