pandas
  1. pandas-seriesmap

Series.map() - Pandas Series

The Series.map() method in Pandas is used to modify existing elements of a Series by applying a function to each element. It works by iterating over each element of the Series and applying the given function to it. The result of the function is used to replace the value of the element in the Series.

Syntax

The syntax for the Series.map() method is as follows:

Series.map(function, na_action=None)
  • function - The function to apply to each element of the Series.
  • na_action - What to do when NaN values are encountered. This can be either 'ignore' to leave NaN values as is or 'raise' to raise a ValueError.

Example

Suppose we have a Pandas Series s that contains the following elements:

import pandas as pd

s = pd.Series([10, 20, 30, 40, 50])

We can use the map() method to apply a function that returns the square of each element in the Series:

s_squared = s.map(lambda x: x**2)

The resulting Series s_squared will contain the squared values of each element:

0     100
1     400
2     900
3    1600
4    2500
dtype: int64

Output

Output of the s_squared Series after applying map() method:

0     100
1     400
2     900
3    1600
4    2500
dtype: int64

Explanation

The Series.map() method applies the given function to each element of a Series to produce a new Series where the original values are replaced with the result of the function. In this example, we applied a lambda function that returns the square of each element, and it returns a new Series where the original values are replaced with their respective squares.

Use

The Series.map() method is useful when we need to apply a custom function to each element of a Pandas Series. It is commonly used to transform the values in a Series for further analysis and exploration.

Important Points

  • The Series.map() method iterates over each element of a Series and applies the function to it.
  • The result of the function is used to replace the value of the element in the Series.
  • The original Series is not modified by the map() method.
  • The map() method can be used in combination with other methods to perform data exploration and analysis.

Summary

The Series.map() method in Pandas is used to apply a function to each element of a Series. It returns a new Series where the original values are replaced with the result of the function. It is highly useful for transforming the values in a Series to perform data analysis and exploration.

Published on: