0
$\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$
1
$\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$
  • $\begingroup$ Thank you, this works! $\endgroup$ – Sca Jun 17 '19 at 5:07
  • $\begingroup$ You may mark the answer as accepted to close the question if your problem is solved. :) $\endgroup$ – bkshi Jun 17 '19 at 5:12
  • $\begingroup$ Yes I did mark the answer as accepted. $\endgroup$ – Sca Jun 18 '19 at 4:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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