P. Prunesquallor
P. Prunesquallor

Reputation: 571

python pandas - get piece of dataframe based on the values in column of other dataframe

Let's say I have df1:

   m  n
0  a  1
1  b  2
2  c  3
3  d  4

and df2:

   n  k
0  1  z
1  2  g

I just want to get the piece of df1 where the values of column 'n' are the same as those present in df2:

   m  n
0  a  1
1  b  2

What's the best way to do this? It seemed trivial beforehand but then surprisingly nothing I tried worked. For example I tried

df1[df1["n"] == df2["n"]]

but this gave me

ValueError: Can only compare identically-labeled Series objects

Upvotes: 2

Views: 111

Answers (1)

BENY
BENY

Reputation: 323396

You are looking for isin

df1.loc[df1.n.isin(df2.n),:]

Upvotes: 3

Related Questions