2

I have the following DataFrame with Index Date and ID

                  V1   V2
Date       ID
01.01.2010  1      x    y
01.01.2010  2      x    y
02.01.2010  1      x    y
        ......

I was able to select a date range with

df.loc[ slice(start, end) ]

But I need to filter data based on a list of ID's. For example

allowed = [1, 5]
df.loc[ allowed ]

How this is possible?

2 Answers 2

2

Use index.isin to check for membership across Index axis. In the case of a multi-index, supply the position of the level or level name explicitly for which the check has to be performed.

df.loc[df.index.isin(allowed, level='ID')]    # level name is specified

(Or)

df.loc[df.index.isin(allowed, level=1)]       # level position is specified
Sign up to request clarification or add additional context in comments.

Comments

1

You can also use .query() method:

In [62]: df
Out[62]:
              V1 V2
Date       ID
2010-01-01 1   x  y
           2   x  y
2010-02-01 1   x  y

In [63]: allowed = [1, 5]

In [64]: df.query("ID in @allowed")
Out[64]:
              V1 V2
Date       ID
2010-01-01 1   x  y
2010-02-01 1   x  y

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.