SoFunction
Updated on 2025-05-06

Implementation of pandas DataFrame map method

Pandas2.2 DataFrame

Function application, GroupBy & window

method describe
(func[, axis, raw, …]) Used to apply a function along the axis (row or column) of a DataFrame
(func[, na_action]) Used to apply a function to each element of a DataFrame

()

()Methods are used to apply a function to each element of a DataFrame. It is the easiest element-by-element operation method and is often used for data conversion or cleaning.

Method signature

(func, na_action=None)

Parameter description

parameter type describe
func function Functions applied to each element of DataFrame.
na_action {None, ‘ignore’}, default: None If'ignore', skipNaNValue, not applied to itfunc

Return value

  • Returns a new DataFrame with the same shape as the original DataFrame, and each element isfuncThe results after application.

Example

Example 1: Simple mapping (such as converting each element into a string)

import pandas as pd

df = ({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
})

# Convert each element to a stringresult = (str)
print(result)

Output:

   A  B
0  1  4
1  2  5
2  3  6

Example 2: Custom function mapping (such as adding 10)

# Add 10 to each elementresult = (lambda x: x + 10)
print(result)

Output:

    A   B
0  11  14
1  12  15
2  13  16

Example 3: Use na_action='ignore' to ignore the NaN value

import numpy as np

df_with_nan = ({
    'A': [1, , 3],
    'B': [, 5, 6]
})

# Add 1 to non-NaN elements onlyresult = df_with_nan.map(lambda x: x + 1, na_action='ignore')
print(result)

Output:

     A    B
0  2.0  NaN
1  NaN  6.0
2  4.0  7.0

Summarize

  • map()Is an ideal tool for one-to-one transformation of each element in a DataFrame.
  • Support skipNaNValues ​​are mapped.
  • Commonly used in format conversion, numerical conversion and other scenarios.

This is the end of this article about the implementation of the pandas DataFrame map method. For more related pandas DataFrame map content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!