Pandas DataFrame.map: Apply a Function Element-wise to a DataFrame
Pandas DataFrame.map
The DataFrame.map
method in pandas is used to apply a function element-wise to a DataFrame. It is primarily used for transforming or mapping values in a DataFrame using a specified function.
Syntax
The syntax for DataFrame.map
is:
DataFrame.map(func, na_action=None, **kwargs)
Here, DataFrame
refers to the pandas DataFrame on which the function is applied.
Parameters
Parameter | Description |
---|---|
func | The function to apply to each element of the DataFrame. This can be a built-in function, a lambda function, or a custom function. |
na_action | Specifies how to handle missing values (NaN ). If set to 'ignore' , the function will not be applied to missing values. Defaults to None . |
**kwargs | Additional keyword arguments to pass to the function. |
Returns
A DataFrame with the same shape as the original, where each element has been transformed by the specified function.
Examples
Applying a Function to Each Element of a DataFrame
This example demonstrates how to use map
to multiply each element in a DataFrame by 2.
Python Program
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# Apply a function to each element of the DataFrame
result = df.map(lambda x: x * 2)
print(result)
Output
A B C
0 2 8 14
1 4 10 16
2 6 12 18
Handling Missing Values in a DataFrame
This example shows how to use the na_action
parameter to ignore missing values when applying a function to a DataFrame.
Python Program
import pandas as pd
# Create a DataFrame with missing values
df = pd.DataFrame({'A': [1, None, 3], 'B': [4, 5, None], 'C': [7, 8, 9]})
# Apply a function to each element, ignoring missing values
result = df.map(lambda x: x * 2, na_action='ignore')
print(result)
Output
A B C
0 2.0 8.0 14
1 NaN 10.0 16
2 6.0 NaN 18
Applying a Custom Function to a DataFrame
This example demonstrates how to use a custom function with map
to transform each element in a DataFrame.
Python Program
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# Define a custom function to square each element
def square(x):
return x ** 2
# Apply the custom function to each element of the DataFrame
result = df.map(square)
print(result)
Output
A B C
0 1 16 49
1 4 25 64
2 9 36 81
Summary
In this tutorial, we explored the DataFrame.map
method in pandas. Key takeaways include:
- Using
map
to apply a function element-wise to a DataFrame. - Handling missing values with the
na_action
parameter. - Applying custom functions to transform DataFrame elements.