7
$\begingroup$
If the data frames are as follows :
df1
column names = UniqueID  Age Gender
values = 213,21,F
         145,34,M
         890,23,F
df2
column names = ID Occupation Bill
               145 Teacher 45RS
               890 Student 70RS 
               456 Teacher 90Rs

I want to use a function which finds the common values in "UniqueID" from df1 and "ID" from df2 and gets stored in df3. Also, the only columns which exist in df3 should be of "common ids" and the columns of df2.

$\endgroup$

2 Answers 2

6
$\begingroup$

You can use pandas.merge() to get the common rows based on the columns. Try this:

df3 = pd.merge(df1, df2, how='inner', left_on='UniqueID', right_on='ID')

However, this will give you all the columns. After that you can use

df3.drop([column_names], inplace=True)

to drop the columns that are not required.

$\endgroup$
3
  • $\begingroup$ Thank you, this works! $\endgroup$
    – Sca
    Jun 17, 2019 at 5:07
  • $\begingroup$ You may mark the answer as accepted to close the question if your problem is solved. :) $\endgroup$
    – bkshi
    Jun 17, 2019 at 5:12
  • $\begingroup$ Yes I did mark the answer as accepted. $\endgroup$
    – Sca
    Jun 18, 2019 at 4:15
2
$\begingroup$
df3 = df1[df['series_name'].isin(df2['series_name'])]

EDIT:

Adding details per request. This simple approach can compare across 2 different dataframes, placing the output in a third.

$\endgroup$
1
  • 1
    $\begingroup$ Can you please add some details around your solution as in, the answer should include some information about the approach and why it was chosen over others. $\endgroup$
    – hH1sG0n3
    Jun 21, 2021 at 15:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.