1

I've asked a similar question in the past, however, its filtering with different conditions. hence, i'm posting this:

I have two dateframe (df1 & df2), i'm trying to figure out how to use conditions from df2 to extract values from df1 and use the extracted values in df2.

df1 = values to exact from

df2 = conditions for exaction and df where the extracted values are used

conditions: df2.ans = df2HJ & df2.P1 = df1 P2 colum

example if df2(df2.HJ = 99 & df2.P1 = 0); Ans = 76 (from df1)

df1

╔════╦════╦══════╦
║ HJ ║ P1 ║  P2  ║
╠════╬════╬══════╬
║  5 ║ 51 ║  33  ║
║ 11 ║ 66 ║  45  ║
║ 21 ║  7 ║  55  ║
║ 99 ║  0 ║  76  ║
║ 15 ║ 11 ║  42  ║
╚════╩════╩══════╩

df2

╔════╦════╗
║ HJ ║ P1 ║
╠════╬════╣
║ 99 ║ 0  ║
║ 11 ║ 66 ║
║  5 ║ 51 ║
║ 21 ║ 7  ║
║ 11 ║ 66 ║
╚════╩════╝

expected result for df2 after exaction from df1

╔════╦════╦═══════╗
║ HJ ║ P1 ║  Ans  ║
╠════╬════╬═══════╣
║ 99 ║ 0  ║   76  ║
║ 11 ║ 66 ║   45  ║
║  5 ║ 51 ║   33  ║
║ 21 ║ 7  ║   55  ║
║ 11 ║ 66 ║   45  ║
╚════╩════╩═══════╝

code for df1

import pandas as pd
import numpy as np
data = {'HJ':[5,11,21,99,15],
'P1':[51,66,7,0,11]
,'P2':[ 33,45,55 ,76 ,42]}
df1 = pd.DataFrame(data)

code for df2

data = {'HJ':[99,11,5,21,11],
'P1':['0','66','51','7','66']}
df2 = pd.DataFrame(data)

Regards Thank you

2
  • Simply use df2.astype({'P1': 'int'}).merge(df1, on=['HJ', 'P1']) Commented Jul 30, 2020 at 12:41
  • Does this answer your question? Pandas Merging 101 Commented Jul 30, 2020 at 12:43

2 Answers 2

1

I don't know why you want this example, cause your expected result its df1 with other order.

But if you want to connect different dataframes, it will be usefull use .join function: Join panda's function

Sign up to request clarification or add additional context in comments.

2 Comments

the original df is much larger and both contain different number of rows and columns. the examples are shorten and simplified vision for easy references understanding. Cheers
the link was very useful and have help rectified the problem. thanks
0

Thanks to @Pol Renau Larrodé pointers i was able to solve the problem.

res = df2.merge(df1, how='inner', left_on=['HJ ', 'P1'], right_on=['HJ ', 'P1'])

Comments

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.