Reputation: 597
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
Upvotes: 1
Views: 38
Reputation: 597
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'])
Upvotes: 0
Reputation: 26
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
Upvotes: 1