Published in


Pandas-Apply and Map

Apply and Map function on a pandas dataframe

Photo by Michał Mancewicz on Unsplash

Apply and Map

Map and reduce are two functions that apply a task that you create to a data frame. Pandas supports functional programming techniques that allow you to use functions across en entire data frame. Pandas also provides several standard functions for use with data frames.

Using Map with Dataframes

The map function allows you to transform a column by mapping certain values in that column to other values. Consider the Auto MPG data set that contains a field origin_name that holds a value between one and three that indicates the geographic origin of each car. We can see how to use the map function to transform this numeric origin into the textual name of each origin.

The map method in Pandas operates on a single column. You provide map with a dictionary of values to transform the target column. The map keys specify what values in the target column should be turned into values specified by those keys. The following code shows how the map function can transform the numeric values of 1, 2, and 3 into the string values of North America, Europe and Asia.

Using Apply with Dataframes

The apply function of the data frame can run a function over the entire data frame. You can use either be a traditional named function or a lambda function. Python will execute the provided function against each of the rows or columns in the data frame. The axis parameter specifies of the function is run across rows or columns. For axis = 1, rows are used. The following code calculates a series called efficiency that is the displacement divided by horsepower.

You can now insert this series into the data frame, either as a new column or to replace an existing column. The following code inserts this new series into the data frame.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store