1

I have data frame like below, where I need to join two tables and create the expected output as shown below and how can this be done

df1

Zone    Country

EU1      AT
EU1      BE
EU1      FR
AP2      IN
AP2      NZ

df2

Origin_Zone  Dest_zone  Key
  EU1          EU1        A
  AP2          EU1        B

Expected output

Org       Dest  Key
AT        AT     A
AT        BE     A
AT        FR     A
BE        AT     A
BE        BE     A
BE        FR     A
FR        AT     A
FR        BE     A
FR        FR     A
IN        AT     B
IN        BE     B
IN        FR     B
NZ        AT     B
NZ        BE     B
NZ        FR     B 

How to create the expected output in pandas

1 Answer 1

2

Use DataFrame.merge by both zones, then rename columns and select expected columns by list:

df = (df2.merge(df1, left_on='Origin_Zone',right_on='Zone')
         .merge(df1, left_on='Dest_zone',right_on='Zone')
         .rename(columns={'Country_x':'Org','Country_y':'Dest'})
         [['Org','Dest','Key']])
print (df)
   Org Dest Key
0   AT   AT   A
1   AT   BE   A
2   AT   FR   A
3   BE   AT   A
4   BE   BE   A
5   BE   FR   A
6   FR   AT   A
7   FR   BE   A
8   FR   FR   A
9   IN   AT   B
10  IN   BE   B
11  IN   FR   B
12  NZ   AT   B
13  NZ   BE   B
14  NZ   FR   B
2
  • You are a Pandas’ superhuman. A collection of your Pandas answers would make the best practical resources available of Pandas library. Sep 18, 2020 at 5:48
  • @PraysonW.Daniel - I dont thinks so, I only code a lot. I think there is many a betters pandas coder like me, but they are obviously too busy.
    – jezrael
    Sep 18, 2020 at 5:49

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.