Boolean comparison of a MultiIndex to one of its values

Viewed 48

I'd like to compare a value of a MultiIndex to the whole index, to get a boolean array for other processing. This works fine for a regular integer index, but for some reason it doesn't compare equal for MultiIndex.

For example:

>>> i = pd.Index([1, 2, 3, 4, 5])
>>> i == i[0]
array([ True, False, False, False, False])

>>> i = pd.Index([(1, 2), (3, 2), (3, 3), (4, 1), (5, 2)])
>>> i == i[0]
array([False, False, False, False, False])

How can I achieve this comparison? I'm sure it is doable with looping through the index, but there's got to be a better way.

1 Answers

This really piqued my interest, and I think I might have come up with a satisfying solution. It involves the use of pandas.MultiIndex.difference

non_matching_tuples = i.difference(pd.Index([i[0]])) # this gets all non-matching indices
desired_output = ~i.isin(non_matching_tuples) # this should give your desired output

Let me know if this satisfies your curiosity, I think it's pretty much what you were looking for.

Related