0

I have DataFrame where are few columns. I have also list of unique elements (elements from one of the columns).

I would like to leave only rows with elements in DataFrame which are included in my list. I tried to do that but all my ideas failed.

Below quick example:

list = ["a", "b"]

Col1 Col2 Col3
1    a     ok
2    b     nok
3    c     ok
4    d     ok
5    a     nok

So I want to keep only rows where are A and B (elements from my list).

0

2 Answers 2

4

Try this:

df.loc[df[column_you_want].isin(your_list)]
Sign up to request clarification or add additional context in comments.

Comments

3
df = df.loc[df["Col2"].isin(["a", "b"])]

will give:

Col1 Col2 Col3
1    a     ok
2    b     nok
5    a     nok

1 Comment

The resulting df will be a view, so mutating the df can give trouble down the line. You should use df.loc instead, so that the return type is a real DataFrame rather than a view.

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.