Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas MultiIndex Lookup By Equality and Set Membership

Given a pandas Series, or Dataframe, with a multiindex:

first_key = ['a', 'b', 'c']
second_key = [1, 2, 3]

m_index = pd.MultiIndex.from_tuples(itertools.product(first_key, second_key),
                                    names=['first_key', 'second_key'])

series_with_index = pd.Series(0.0, index=m_index)

How can the MultiIndex be indexed to lookup an equality for the first level and an isin on the second index?

For example, how can all values where the first level is equal to a and the second level is in the set {2, 3, 4} be set to 1.0?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you in advance for your consideration and response.

>Solution :

Try this:

you can use index.get_level_values() to find all the values in the first level that equal a.

index.isin() has a level parameter, so you can pass your set into that.

lastly change the values in the series to 1 where they are both True

m1 = series_with_index.index.get_level_values(0) == 'a'
m2 = series_with_index.index.isin({2,3,4},level=1)

series_with_index.mask(m1 & m2,1)

Output:

first_key  second_key
a          1             0.0
           2             1.0
           3             1.0
b          1             0.0
           2             0.0
           3             0.0
c          1             0.0
           2             0.0
           3             0.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading