Pandas数据框:检查索引是否存在于多级索引中

14

我有一个pandas数据帧,它使用列useriditemid创建了一个多级索引。df看起来像这样

                  0     1     2
userid  itemid
007     5000      9     4     3
007     4000      6     7     1
009     3000      1     2     3

我想检查数据框df中是否存在索引[007, 6000]。我该怎么做?如果我运行以下代码会出现错误TypeError: unhashable type: 'list'

if [007, 6000] in df.index:
    print('it works')

pandas 中惯用的 in/not in 是 isin。另外,它们是整数还是字符串? - cs95
3个回答

19

针对此事 -

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)
您可以使用df.index.isin
df.index.isin([(7, 5000)])
array([ True, False, False], dtype=bool)

这会给你一个与值的位置对应的掩码。如果你只想知道它是否存在,可以使用np.ndarray.any结合isin使用。

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

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

1
我尝试了这种方法,但出现了错误,显示 TypeError: object of type 'numpy.int64' has no len() - user77005
@user77005,我的代码中根本没有len这个部分。你在运行什么? - cs95
我的错误。我没有将索引作为元组给出。你的建议有效。 - user77005
有没有办法可以传递一个字典而不是元组?如果您不必担心索引级别的顺序,那将非常好。 - skatenerd

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

0

pd.MultiIndex 转换为 list 并检查其是否存在于 list

代码

import pandas as pd

mi = pd.MultiIndex.from_tuples(
    [(7, 5000), (7, 4000), (8, 3000)], names=['usedId', 'itemId'])
df = pd.DataFrame([[9, 4, 3], [6, 7, 1], [1, 2, 3]], index=mi)

print('df:', df, sep='\n', end='\n\n')
print('mi:', mi, sep='\n', end='\n\n')

print('Check for elements in Multi-Index:')
print('\t(7, 4000) in mi.to_list():', (7, 4000) in mi.to_list())
print('\t(7, 99) in mi.to_list():', (7, 99) in mi.to_list())

输出

df:
               0  1  2
usedId itemId         
7      5000    9  4  3
       4000    6  7  1
8      3000    1  2  3

mi:
MultiIndex([(7, 5000),
            (7, 4000),
            (8, 3000)],
           names=['usedId', 'itemId'])

Check for elements in Multi-Index:
    (7, 4000) in mi.to_list(): True
    (7, 99) in mi.to_list(): False

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接