Pandas Tricks — Pass Multiple Columns To Lambda

4 min readJul 18, 2020

Pandas is one of the most powerful tool for analyzing and manipulating data. In this article, I will be sharing with you the solutions for a very common issues you might have been facing with pandas when dealing with your data — how to pass multiple columns to lambda or self-defined functions.


You will have to install pandas on your working environment:

pip install pandas

When dealing with data, you will always have the scenario that you want to calculate something based on the value of a few columns, and you may need to use lambda or self-defined function to write the calculation logic, but how to pass multiple columns to lambda function as parameters?

Let me use some real world example, so that easier for you to understand the issue that I am talking about. Below table shows partial of the e-com delivery charges offered by some company, so the delivery charges are determined by package size (H+L+W), package weight and the delivery mode you are choosing.

And assuming we have the below order data, and we want to simulate the delivery charges. Let’s create the data in a pandas dataframe.

import pandas as pddf = pd.DataFrame({ "Order#" : ["1", "2", "3", "4"], "Weight" : [5.0, 2.1, 8.1, 7.5], "Package Size" : [80, 45, 110, 90], "Delivery Mode": ["Same Day", "Next Day", "Express", "Next Day"]})

If you view dataframe from Jupyter Notebook (you can sign up here to use it for free), you shall be able to see the data as per below.

Let’s also implement a calculate_rate function where we need to pass in the weight, package size, and delivery mode in order to calculate the delivery charges:

def calculate_rate(weight, package_size, delivery_mode): 
#set the charges as $20 since we do not have the complete rate card
charges = 20
if weight <=1 and package_size <60:
if delivery_mode == "Express":
charges = 13
elif delivery_mode == "Next Day":
charges = 8…

Resources and tutorials for python, data science and automation solutions

Recommended from Medium