Coding Ref

How to use pandas map() function

How to use pandas map() function

The map() function is a built-in Python function that allows you to apply a function to every element of an iterable, such as a list or a Pandas Series.

We will learn about the map() function and how to use it in Pandas to transform data.

To illustrate, let's create a simple Pandas Series with some random data:

main.py
import pandas as pd

# create a Series with some random data
s = pd.Series([1, 2, 3, 4, 5])

# print the Series
print(s)

The resulting Series will look like this:

output
0    1
1    2
2    3
3    4
4    5

dtype: int64

Now, let's use the map() function to apply a function to every element of the Series. For example, let's say we want to square each element in the Series. To do this, we can use the map() function and pass it the pow() function with the second argument set to 2:

main.py
# square each element in the Series
squared = s.map(pow, 2)

# print the result
print(squared)

This will output the squared values of each element in the Series:

output
0     1
1     4
2     9
3    16
4    25

dtype: int64

In this case, the map() function applies the pow() function to each element of the Series, which squares each element and returns a new Series with the squared values.

You'll also like

Related tutorials curated for you

    How to select multiple columns in Pandas

    How to apply a function to multiple columns in Pandas

    What is isna() in Pandas?

    How to convert a series to a list in Pandas

    How to use Timedelta in Pandas

    How to stack two Pandas DataFrames

    How to split a Pandas DataFrame by a column value

    fillna() in Pandas

    How to GroupBy Index in Pandas

    How to make a crosstab in Pandas

    How to find the minimum in Pandas

    How to round in Pandas