import pandas as pd
voters = pd.read_excel("data/vlookup-example.xls",sheet_name="Voters")
party_name = pd.read_excel("data/vlookup-example.xls", sheet_name = "Party Codes")
I have a very basic spread sheet with two sheets one called Voters and one called Party Codes. and I want to look up the party name based on the party code for the voters. lets look at the data to get a better understanding of this.
as you can see below the goal here is to fill in the "Political Party" Column
voters
party_name.head()
In pandas to mimic the functionality of a vlookup we use a method called merge, as the name suggest merge method merges or combines two or more tables togather
pd.merge(left = voters, right = party_name, left_on ="Pcode", right_on = "PARTY CODE" , how="left")
There we go we just joined the two tables together, but it's not neat, I want the NAME column to be in Politcal Party
pd.merge(left = voters, right = party_name, left_on ="Pcode", right_on = "PARTY CODE", how="left").loc[:,["First","Last","Pcode","NAME"]].rename(columns={"NAME":"Political Party"})