Home >Backend Development >Python Tutorial >How Do `map`, `applymap`, and `apply` Differ in Pandas Vectorization?

How Do `map`, `applymap`, and `apply` Differ in Pandas Vectorization?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-07 03:09:10718browse

How Do `map`, `applymap`, and `apply` Differ in Pandas Vectorization?

Vectorization Methods in Pandas: map, applymap, and apply

Pandas offers convenient methods for applying functions to data structures. map, applymap, and apply are three such methods that facilitate data manipulation and transformation. Each method serves a specific purpose, and their usage depends on the desired outcome.

map

map is employed when applying a function element-wise to a Series. It returns a new Series with the transformed values.

Example:

import pandas as pd

series = pd.Series([1, 2, 3, 4, 5])

def square(x):
    return x ** 2

squared_series = series.map(square)

print(squared_series)
# Output:
# 0    1
# 1    4
# 2    9
# 3   16
# 4   25
# dtype: int64

applymap

applymap applies a function element-wise to a DataFrame. It creates a new DataFrame with the transformed values.

Example:

df = pd.DataFrame({
    'name': ['John', 'Jane', 'Tom'],
    'age': [20, 25, 30]
})

def capitalize(x):
    return x.capitalize()

df['name'] = df['name'].applymap(capitalize)

print(df)
# Output:
#    name  age
# 0  John   20
# 1  Jane   25
# 2  Tom    30

apply

apply allows for more complex transformations by applying a function row- or column-wise to a DataFrame. It returns a Series or DataFrame with the results.

Example:

def get_age_group(age):
    if age <= 20:
        return 'Young'
    elif age <= 40:
        return 'Middle-aged'
    else:
        return 'Senior'

df['age_group'] = df['age'].apply(get_age_group)

print(df)
# Output:
#   name  age age_group
# 0  John   20     Young
# 1  Jane   25  Middle-aged
# 2  Tom    30  Middle-aged

The above is the detailed content of How Do `map`, `applymap`, and `apply` Differ in Pandas Vectorization?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn