CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Follow publication

3 One-liner Python Functions You Should Know (and Implement)

Learn when and how to use Map, ApplyMap, and Apply function in Python

Anmol Tomar
CodeX
Published in
4 min readJul 19, 2022
Image Credits: Unsplash

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:

  1. Map
  2. Applymap
  3. 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 —

  1. mapping_func : Mapping function that contains the mapping logic. This is usually a dictionary of key-value pairs.
  2. 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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

CodeX
CodeX

Published in CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Anmol Tomar
Anmol Tomar

Written by Anmol Tomar

Top AI writer | Data Science Manager | Mentor. Want to kick off your career in Data Science? Get in touch with me: https://www.analyticsshiksha.com/

Responses (2)

Write a response