简体   繁体   中英

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

您在寻找isin

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM