2

supposed data set,

df1

num1 num2
27    1
973   3
1410  3
724   1
346   5

df2

 a1     a2   c1      c2
27.0    1   red    apple
131.0   1   blue   banana
2124.0  3   green  apple
1345.0  1   red    orange
346.0   5   blue   grape

I want to compare num1 - a1 & num2 - a2, If both conditions are the same, I want to add the values in c1 and c2 to the list.(assume the beginning is an empty list)

condition

  1. As you see, num1-a1, num2&a2 `s shape is different.

  2. Only the values added to the list are 'c1' and 'c2'

    (num1, num2, a1, a2 are just using to compare & match)

  3. The order is jumbled, and the dataframes are different sizes. (different column length)

The Output what I want

above example, 2 matches, (27-1 , 346-5), so

mylist = [red, apple, blue, grape]

How can I do this?

Thank you for reading.

1
  • It seems 'blue', 'banana' is also matched. Commented Feb 3, 2020 at 9:14

1 Answer 1

2

Use Series.str.zfill with DataFrame.assign for add 0 for matched with df2, then DataFrame.merge with defualt join, last use DataFrame.stack for Series and convert to list:

mylist = (df1.assign(num1 = df1['num1'].astype(str).str.zfill(4),
                     num2 = df1['num2'].astype(str).str.zfill(3))
              .merge(df2, left_on=['num1','num2'], right_on=['a1','a2'])[['c1','c2']]
              .stack()
              .tolist())
print (mylist)
['green', 'apple', 'orange', 'melon',
 'blue', 'banana', 'purple', 'peach']
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your efficient code , but now I am reading real data, I modified my question to be a little different from the shape I thought. Can you check again if it`s okay?
@ybin - I see your answer and it is correct, only omit .assign(num1 = df1['num1'].astype(str).str.zfill(4), num2 = df1['num2'].astype(str).str.zfill(3))

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.