Home >Backend Development >Python Tutorial >How Do Pandas' `map`, `applymap`, and `apply` Methods Differ?
Understanding the Differences Between Map, Applymap, and Apply Methods in Pandas
When working with vectorization in Pandas, it's crucial to understand the distinctions between the map, applymap, and apply methods. These methods provide flexible ways to apply functions element-wise or row/column-wise to DataFrames and Series.
Map:
Map is a Series method designed for element-wise operations. It takes a function and applies it to each element in a Series. Consider the following example:
import pandas as pd series = pd.Series([1, 2, 3, 4, 5]) squared_series = series.map(lambda x: x ** 2) print(squared_series)
Output:
0 1 1 4 2 9 3 16 4 25 dtype: int64
Applymap:
Applymap is a DataFrame method that performs element-wise operations on the entire DataFrame. It applies the specified function to each individual element within the DataFrame:
dataframe = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6] }) formatted_dataframe = dataframe.applymap(lambda x: f'{x:.2f}') print(formatted_dataframe)
Output:
A B 0 1.00 4.00 1 2.00 5.00 2 3.00 6.00
Apply:
Unlike map and applymap, apply operates on rows or columns of a DataFrame. It takes a function and applies it to each row or column, depending on the axis parameter specified:
# Apply function to each row row_max = dataframe.apply(lambda row: row.max(), axis=1) print(row_max) # Apply function to each column col_min = dataframe.apply(lambda col: col.min(), axis=0) print(col_min)
Output:
0 3 1 5 2 6 dtype: int64 A 1 B 4 dtype: int64
Usage Considerations:
The above is the detailed content of How Do Pandas' `map`, `applymap`, and `apply` Methods Differ?. For more information, please follow other related articles on the PHP Chinese website!