Multiply columns based on two columns conditions from different dataframes?

Viewed 381

I have two dataframes as indicated below:

dfA = 
Country      City           Pop
US           Washington     1000
US           Texas          5000
CH           Geneva         500
CH           Zurich         500


dfB = 
Country      City           Density (pop/km2)
US           Washington     10
US           Texas          50
CH           Geneva         5
CH           Zurich         5

What I want is to compare the columns Country and City from both dataframes, and when these match such as:

US Washington & US Washington in both dataframes, it takes the Pop value and divides it by Density, as to get a new column area in dfB with the resulting division. Example of first row results dfB['area km2'] = 100

I have tried with np.where() but it is nit working. Any hints on how to achieve this?

3 Answers

Using index matching and div

match_on = ['Country', 'City']
dfA = dfA.set_index(match_on)
dfA.assign(ratio=dfA.Pop.div(df.set_index(['Country', 'City'])['Density (pop/km2)']))

Country  City      
US       Washington    100.0
         Texas         100.0
CH       Geneva        100.0
         Zurich        100.0
dtype: float64

You can also use merge to combine the two dataframes and divide as usual:

dfMerge = dfA.merge(dfB, on=['Country', 'City'])
dfMerge['area'] = dfMerge['Pop'].div(dfMerge['Density (pop/km2)'])
print(dfMerge)

Output:

  Country        City   Pop  Density (pop/km2)   area
0      US  Washington  1000                 10  100.0
1      US       Texas  5000                 50  100.0
2      CH      Geneva   500                  5  100.0
3      CH      Zurich   500                  5  100.0

you can also use merge like below

dfB["Area"] = dfB.merge(dfA, on=["Country", "City"], how="left")["Pop"] / dfB["Density (pop/km2)"]
dfB
Related