0

I have a question about merging two tables. Say I have a table A with data consisting of these parameters: Country, City, Zip Code. Also, I have a table B with unique Country names and a column that specifies which continent it is located (NA, Asia, EU, etc..)

How can I merge the two tables into one such that I will have columns: Country, City, Zip Code and a column that corresponds to the continent of table B?

Many thanks!

  • 1
    You probably want A.merge(B, on="Country") But when you have such a generic question you should immediately think of searching before posting a new question. Look here for great info to get exactly what you need : https://stackoverflow.com/questions/53645882/pandas-merging-101 – user2677285 Dec 04 '19 at 03:34

1 Answers1

0

You can make use of the pd.merge function Example: You have a "country" df with "country", "city" and "zip" columns and "continent" df with "country" and "continent" columns. Use the pd.merge function on the common column "country"

country = pd.DataFrame([['country1','city1','zip1'],['country1','city1','zip2'],['country1','city2','zip3'],['country1','city2','zip4'],
                       ['country2','city3','zip5'],['country2','city3','zip6'],['country2','city4','zip7'],
                       ['country3','city5','zip8'],['country3','city6','zip9']],
                      columns=['country','city','zipcode'])
continent = pd.DataFrame([['country1','A'],['country2','B'],['country3','C'],['country4','D'],['country5','E']],
                      columns=['country','continent'])
country = country.merge(continent, on=['country'])
print(country)

Output:

    country   city zipcode continent
0  country1  city1    zip1         A
1  country1  city1    zip2         A
2  country1  city2    zip3         A
3  country1  city2    zip4         A
4  country2  city3    zip5         B
5  country2  city3    zip6         B
6  country2  city4    zip7         B
7  country3  city5    zip8         C
8  country3  city6    zip9         C
davidbilla
  • 2,120
  • 1
  • 15
  • 26