JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Differences between Pandas apply, map and applymap

Author:JIYIK Last Updated:2025/05/02 Views:

This tutorial explains the difference between the apply(), map(), and methods in Pandas.applymap()

The function associated with applymap()is applied to all elements of a given DataFrame, hence applymap()the method is defined only for DataFrames. Similarly, apply()the function associated with the method can be applied to Seriesall elements of a DataFrame or , hence apply()the method is defined for Series and DataFrame objects. The method in Pandas can be defined map()only for SeriesDataFrame objects.

import pandas as pd

df = pd.DataFrame(
    {
        "Col 1": [30, 40, 50, 60],
        "Col 2": [23, 35, 65, 45],
        "Col 3": [85, 87, 90, 89],
    },
    index=["A", "B", "C", "D"],
)

print(df, "\n")

Output:

   Col 1  Col 2  Col 3
A     30     23     85
B     40     35     87
C     50     65     90
D     60     45     89

We will use the DataFrame shown in the above example dfto explain the difference between the apply(), map(), and methods in Pandas.applymap()


pandas.DataFrame.applymap()

grammar

DataFrame.applymap(func, na_action=None)

It funcapplies the function DataFrameto each element of .

Example: Using applymap()the method to change the elements in a DataFrame

import pandas as pd

df = pd.DataFrame(
    {
        "Col 1": [30, 40, 50, 60],
        "Col 2": [23, 35, 65, 45],
        "Col 3": [85, 87, 90, 89],
    },
    index=["A", "B", "C", "D"],
)

print("Initial DataFrame:")
print(df, "\n")

scaled_df = df.applymap(lambda a: a * 10)

print("Scaled DataFrame:")
print(scaled_df, "\n")

Output:

Initial DataFrame:
   Col 1  Col 2  Col 3
A     30     23     85
B     40     35     87
C     50     65     90
D     60     45     89

Scaled DataFrame:
   Col 1  Col 2  Col 3
A    300    230    850
B    400    350    870
C    500    650    900
D    600    450    890

It dfmultiplies each element in the DataFrame and stores the result scaled_dfin the DataFrame. We lambdapass a function as an argument to applymap()the function which returns a value by 10multiplying the input value with . So dfeach element in the DataFrame will be scaled to 10.

We can also use forloop to iterate dfeach element in DataFrame, but it makes our code less readable, messy, and less efficient. applymap()is another alternative that can make the code more readable and efficient.

In addition to mathematical operations, we can also perform other operations on the elements of a DataFrame.

import pandas as pd

df = pd.DataFrame(
    {
        "Col 1": [30, 40, 50, 60],
        "Col 2": [23, 35, 65, 45],
        "Col 3": [85, 87, 90, 89],
    },
    index=["A", "B", "C", "D"],
)

print("Initial DataFrame:")
print(df, "\n")

altered_df = df.applymap(lambda a: str(a) + ".00")

print("Altered DataFrame:")
print(altered_df, "\n")

Output:

Initial DataFrame:
   Col 1  Col 2  Col 3
A     30     23     85
B     40     35     87
C     50     65     90
D     60     45     89

Altered DataFrame:
   Col 1  Col 2  Col 3
A  30.00  23.00  85.00
B  40.00  35.00  87.00
C  50.00  65.00  90.00
D  60.00  45.00  89.00

It dfis added at the end of each element in the DataFrame .00.


map()Methods in Pandas

import pandas as pd

df = pd.DataFrame(
    {
        "Col 1": [30, 40, 50, 60],
        "Col 2": [23, 35, 65, 45],
        "Col 3": [85, 87, 90, 89],
    },
    index=["A", "B", "C", "D"],
)

print("Initial DataFrame:")
print(df, "\n")

df["Col 1"] = df["Col 1"].map(lambda x: x / 100)

print("DataFrame after altering Col 1:")
print(df)

Output:

Initial DataFrame:
   Col 1  Col 2  Col 3
A     30     23     85
B     40     35     87
C     50     65     90
D     60     45     89

DataFrame after altering Col 1:
   Col 1  Col 2  Col 3
A    0.3     23     85
B    0.4     35     87
C    0.5     65     90
D    0.6     45     89

We can use the method only on specific columns of a DataFrame map().


apply()Methods in Pandas

apply()Methods to change the entire DataFrame in Pandas

import pandas as pd

df = pd.DataFrame(
    {
        "Col 1": [30, 40, 50, 60],
        "Col 2": [23, 35, 65, 45],
        "Col 3": [85, 87, 90, 89],
    },
    index=["A", "B", "C", "D"],
)

print("Initial DataFrame:")
print(df, "\n")

altered_df = df.apply(lambda x: x / 100)

print("Altered DataFrame:")
print(altered_df, "\n")

Output:

Initial DataFrame:
   Col 1  Col 2  Col 3
A     30     23     85
B     40     35     87
C     50     65     90
D     60     45     89

Altered DataFrame:
   Col 1  Col 2  Col 3
A    0.3   0.23   0.85
B    0.4   0.35   0.87
C    0.5   0.65   0.90
D    0.6   0.45   0.89

apply()Method to modify only one column in Pandas

import pandas as pd

df = pd.DataFrame(
    {
        "Col 1": [30, 40, 50, 60],
        "Col 2": [23, 35, 65, 45],
        "Col 3": [85, 87, 90, 89],
    },
    index=["A", "B", "C", "D"],
)

print("Initial DataFrame:")
print(df, "\n")

df["Col 1"] = df["Col 1"].apply(lambda x: x / 100)

print("DataFrame after altering Col 1:")
print(df)

Output:

Initial DataFrame:
   Col 1  Col 2  Col 3
A     30     23     85
B     40     35     87
C     50     65     90
D     60     45     89

DataFrame after altering Col 1:
   Col 1  Col 2  Col 3
A    0.3     23     85
B    0.4     35     87
C    0.5     65     90
D    0.6     45     89

So, from the above examples, we can see that apply()methods can be used to apply a particular function to all the elements of the entire DataFrame or all the elements of a particular column.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to Convert DataFrame Column to String in Pandas

Publish Date:2025/05/02 Views:161 Category:Python

We will look at methods for converting Pandas DataFrame columns to strings. Pandas Series.astype(str) Method DataFrame.apply() Methods operate on the elements in a column We will use the same DataFrame below in this article. import pandas a

How to count the frequency of values in a Pandas DataFrame

Publish Date:2025/05/02 Views:84 Category:Python

Sometimes, when you use DataFrame , you may want to count the number of times a value occurs in a column, or in other words, calculate the frequency. There are mainly three methods used for this. Let's look at them one by one. df.groupby().

How to get value from Pandas DataFrame cell

Publish Date:2025/05/02 Views:147 Category:Python

We'll look at using to get values ​​from cells in iloc Pandas , which is great for selecting by position, and how it differs from . We'll also learn about the and methods, which we can use when we don't want to set the return type to .

How to Add a Row to a Pandas DataFrame

Publish Date:2025/05/02 Views:127 Category:Python

Pandas is designed to load a fully populated DataFrame . We can pandas.DataFrame add them one by one in . This can be done by using various methods, such as .loc , dictionary, pandas.concat() or DataFrame.append() . .loc [index] Add rows to

How to change the order of Panas DataFrame columns

Publish Date:2025/05/02 Views:184 Category:Python

We will show how to use insert and reindex to change the order of columns in different ways pandas.DataFrame , such as assigning column names in a desired order. pandas.DataFrame Sort the columns in the new order The easiest way is columns

How to pretty print an entire Pandas Series/DataFrame

Publish Date:2025/05/02 Views:167 Category:Python

We will introduce various methods to pretty print the entire Pandas Series/DataFrame, such as option_context, set_option, and options.display. option_context Pretty Printing Pandas DataFrame We can option_context use with one or more option

How to Convert a Pandas Dataframe to a NumPy Array

Publish Date:2025/05/02 Views:151 Category:Python

We will introduce to_numpy() the method to pandas.Dataframe convert a to NumPy an array, which is introduced in pandas v0.24.0, replacing the old .values method. We can define it on Index , Series , and DataFrame objects to_numpy . The old

How to add a header row to a Pandas DataFrame

Publish Date:2025/05/02 Views:161 Category:Python

We will look at methods for adding a header row to a pandas dataframe, as well as the option to pass in the names directly in the dataframe or by assigning the column names in a list directly to dataframe.columns the method. We will also in

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial