1

I have two dataframes as follows:

df1:

col1 col2
ABC 1
def 22
def 32
aac 53
ddf 53
tefg 53

df2:

col1
ABC
def
aac
ddf
tefg

Now I want to retain rows in df1, such that value of column "col1" in df1, is present in df2 "col2"

Is there a simple straightforward way to achieve it in Python?

Currently, I am doing it in a brute way with 2 nested for loops, but it is computationally intensive.

1 Answer 1

2

You can do:

df1[df1.col1.isin(df2.col1)]

Example:

Create df1:

data = {'col1': ['a','b','c','d'],
        'col2': [1,2,3,4]}
df1 = pd.DataFrame(data)

and df2:

df2 = pd.DataFrame({'col1': ['a','d']})

then df1[df1.col1.isin(df2.col1)] will be:

  col1  col2
0    a     1
3    d     4
Sign up to request clarification or add additional context in comments.

2 Comments

what is df in here?
Sorry, typo, edited my answer.

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.