Often times, a new user to Python will wish to replicate analysis previously done in Excel. Two major instances of this are the VLOOKUP and SUMIF commands.
- VLOOKUP: Combining data through a common index
- SUMIF: Summing up values by category
Let’s take a look at how we can replicate these commands in Python. You will see that the pandas library offers quite a degree of flexibility when it comes to summarizing and wrangling data in Python in this way.
Firstly, we will import our libraries as standard, set our file path, and import the relevant datasets:
import pandas as pd
import numpy as np
import os;
os.getcwd()
path='/home/michaeljgrogan/Documents/a_documents/computing/data science/datasets'
os.chdir(path)
sales=pd.read_csv('sales.csv')
sales
customers=pd.read_csv('customers.csv')
customers
Note that the datasets “customers.csv” and “sales.csv” are available on the “Datasets” page.
VLOOKUP with merge
In the sales dataset, you will notice that we have Date, ID and Sales figures. In the customers dataset, we also have a corresponding ID variable, but we do not have a date column.
Suppose that we wish to combine the “Date” variable in the sales dataset to the rest of the data in the customers dataset. Ordinarily, we would use VLOOKUP or INDEX-MATCH in Excel to do this. However, let us see how this can be done in Python:
#VLOOKUP sales.merge(customers, on='ID', how='right')
Once we have done this, you will see that we have the two datasets merged, with the Date variable on the left and the rest of the data on the right:
>>> sales.merge(customers, on='ID', how='right')
Date ID Sales Age Country
0 2014-02-12 49 113769 23 Trinidad and Tobago
1 2014-02-14 57 122965 46 Singapore
2 2014-03-18 2 164556 28 Lao PDR
.. ... .. ... ... ...
98 2016-12-06 32 126092 33 Saint Vincent and Grenadines
99 2016-12-27 45 117126 47 Iran, Islamic Republic of
SUMIF with groupby
Often times, an Excel user will use the SUMIF function to sum up different values by category. This can also be replicated in Python.
Let’s firstly create a new dataframe in pandas:
df1 = pd.DataFrame({'names': ['John', 'Elizabeth', 'Michael', 'John', 'Elizabeth', 'Michael'], 'webvisits': ['24', '32', '40', '71', '65', '63'], 'minutesspent': ['20', '41', '5', '6', '48', '97']}, index=[0, 1, 2, 3, 4, 5])
Essentially, what we wish to do here is group by name, and get the total “minutesspent” for each person.
#SUMIF
df1.groupby("names")["minutesspent"].sum()
Now, we have our results:
names Elizabeth 4148 John 206 Michael 597 Name: minutesspent, dtype: object
Further Reading
Thanks for viewing this short tutorial, and please leave any questions in the comments below!

Leave a Reply