The applymap()
function in Pandas is used to apply a function to every element in a dataframe.
Here's an example:
import pandas as pd
# create a sample dataframe
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# define a function that will be applied to each element
def add_one(x):
return x + 1
# apply the function to the dataframe using applymap()
df_new = df.applymap(add_one)
print(df_new)
The resulting dataframe df_new
will have all its elements incremented by one:
0 1 2
0 2 3 4
1 5 6 7
2 8 9 10
You can also use a lambda function with applymap()
like this:
# apply a lambda function to the dataframe using applymap()
df_new = df.applymap(lambda x: x + 1)
print(df_new)
The resulting dataframe will be the same as before.
applymap()
only works element-wise and will not work with functions that expect Series
or DataFrame
objects as input. In that case, you can use the apply()
method instead.
Related tutorials curated for you
Pandas read SQL
How to stack two Pandas DataFrames
How to change the order of columns in Pandas
How to concatenate in Pandas
What does Head() do in Pandas?
How to round in Pandas
How to add an empty column to a Pandas DataFrame
How to use intertuples() in Pandas
How to read a TSV file in Pandas
How to use nunique() in Pandas
How to convert a Pandas Index to a List
How to convert Pandas timestamp to datetime