ajwood
ajwood

Reputation: 19057

Testing if one Pandas (Multi)Index is a subset of another

How can I test if one pandas (Multi)Index is a subset of another. The order doesn't matter, as long as the values exist.

import pandas as pd
import numpy as np

df0 = pd.DataFrame( np.random.rand(3,10), index=['foo', 'bar', 'baz'] )
df1 = pd.DataFrame( np.random.rand(2,10), index=['baz', 'foo'])
df2 = pd.DataFrame( np.random.rand(3,10), index=['foo', 'baz', 'BLAH'] )

issubset(df0.index,  df1.index)  # True
issubset(df0.index,  df2.index)  # False

Upvotes: 2

Views: 1068

Answers (2)

C8H10N4O2
C8H10N4O2

Reputation: 19045

Try set.issubset, as in:

set(df1.index).issubset(set(df0.index)) # True
set(df0.index).issubset(set(df2.index)) # False

Because a pandas.Index is an (ordered) array, you want to convert it to an (unordered) set and then use issubset.

Upvotes: 2

Scott Boston
Scott Boston

Reputation: 153560

You can use isin and all:

df1.index.isin(df0.index).all()

True

df2.index.isin(df0.index).all()

False

Upvotes: 3

Related Questions