Check if a value exists in pandas dataframe index

前端 未结 6 813
轮回少年
轮回少年 2020-12-23 13:17

I am sure there is an obvious way to do this but cant think of anything slick right now.

Basically instead of raising exception I would like to get True

6条回答
  •  悲&欢浪女
    2020-12-23 13:37

    Multi index works a little different from single index. Here are some methods for multi-indexed dataframe.

    df = pd.DataFrame({'col1': ['a', 'b','c', 'd'], 'col2': ['X','X','Y', 'Y'], 'col3': [1, 2, 3, 4]}, columns=['col1', 'col2', 'col3'])
    df = df.set_index(['col1', 'col2'])
    

    in df.index works for the first level only when checking single index value.

    'a' in df.index     # True
    'X' in df.index     # False
    

    Check df.index.levels for other levels.

    'a' in df.index.levels[0] # True
    'X' in df.index.levels[1] # True
    

    Check in df.index for an index combination tuple.

    ('a', 'X') in df.index  # True
    ('a', 'Y') in df.index  # False
    

提交回复
热议问题