Member-only story
3 One-liner Python Functions You Should Know (and Implement)
Learn when and how to use Map, ApplyMap, and Apply function in Python

In Data Processing, we often transform our data by applying certain operations and transformations on a python series or data frame. To perform some of these transformations we might use the loops in python.
Using loops to iterate through a dataframe or series is not recommended for performing the transformations as the loop takes more lines of code, affects readability, and reduces performance. Fortunately, there are some python functions that overcome these challenges and come in really handy in transforming the data effectively.
In this blog, I will talk about how to use the following one-liner functions:
- Map
- Applymap
- Apply
Even if you have heard about these functions there is no harm in refreshing your knowledge.
1. Map
The map function is used to swap(or map) each value in a series with another value. The map function is applied to a series only.
Syntax
Map function takes 2 arguments —
- mapping_func : Mapping function that contains the mapping logic. This is usually a dictionary of key-value pairs.
- na_action: If set to ‘ignore’, the mapping function is not applied to NaN values in a series.
Series.map(mapping_func, na_action = None)
How to use
#import packages
import pandas as pd
import numpy as np# creating a series
s = pd.Series(['Math', 'Science', 'Computer'])# Output of s
#0 Math
#1 Science
#2 Computer# mapping value of a series
s = s.map({'Math': 'Algebra', 'Science':'Physics', 'Computer': 'Python'})# output
#0 Algebra
#1 Physics
#2 Python
Application in data analysis
We can use the map function to apply ordinal encoding on a column of a data frame. For example, we can convert the education column of our salary data frame(below) into…