简体   繁体   中英

Get appropriate data for each row in pandas dataframe from another dataframe

Lets say I have two dataframes in pandas. One df1 contains airports with other informations and I have another dataframe df2 which contains the location of these airports (latitutde,longitude). I would like to assign to each row in df1 the appropriate data from df2 , how can I do that more elegantly and faster than looping over all the possibilities? Two example image is shown below:

Example of df1

Example of df2

    ORIGIN  DEST    DIVERTED
0   ANC     SEA     0
1   LAX     PBI     0
2   SFO     CLT     1


        IATA    LATITUDE    LONGITUDE
  17    ANC     61.17432    -149.99619
  277   SEA     47.44898    -122.30931
  176   LAX     33.94254    -118.40807
  235   PBI     26.68316    -80.09559
  278   SFO     37.619      -122.37484
  66    CLT     35.21401    -80.94313

Lets say you have the following two dataframes:

df1:

  IATA info1 info2 info3
0  ABI   bla   bla   bla
1  ABE   bla   bla   bla

df2:

  IATA  lat  long
0  ABE   40    90
1  ABI   20   100

You can use the following code to merge these two dataframes:

dfNew = pd.merge(df1, df2, on='IATA', how='left')

Output:

  IATA info1 info2 info3  lat  long
0  ABI   bla   bla   bla   20   100
1  ABE   bla   bla   bla   40    90

In your case the following will do:

dfNew = pd.merge(df1, df2, left_on='ORIGIN', right_on='IATA', how='left').drop('IATA', axis=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM