PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 17, 2022

[FIXED] What is the best way to slice a multiindex dataframe using a list of partial index tuples?

 May 17, 2022     multi-index, pandas, partial, python, slice     No comments   

Issue

I want to slice a data frame using a partially matching index, or list of tuples.

_ix = [('foo','a', 1), ('foo','a', 2), ('foo','b', 1), 
       ('foo','b', 2), ('foo','c', 1), ('foo','c', 2)]
df = pd.DataFrame(np.ones((6, 1)), index=pd.MultiIndex.from_tuples(_ix))
print(df)

           0
foo a 1  1.0
      2  1.0
    b 1  1.0
      2  1.0
    c 1  1.0
      2  1.0

Given a query index like:

q_ix = [('foo', 'a'), ('foo', 'c')]

I want to obtain

           0
foo a 1  1.0
      2  1.0
    c 1  1.0
      2  1.0

I can get this by using pd.concat and a list comprehension...

df_sliced = pd.concat([df.loc[(*x, slice(None)), :] for x in q_ix])

...but this is super clunky when my query index is large. Is there no better way?


Solution

Here is one way

df.reset_index(level=2).loc[q_ix].set_index('level_2',append=True)
                 0
      level_2     
foo a 1        1.0
      2        1.0
    c 1        1.0
      2        1.0


Answered By - BENY
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing