Member-only story
The map()
transform values in a Series or DataFrame based on a mapping or function. With it, we can apply custom transformations to our data.
Syntax:
Series.map(arg, na_action=None)
arg
: This parameter can take one of the following:
- A dictionary: It maps current values to new values.
2. A Series: It uses the Series values to perform the mapping.
3. A function: It applies the function to each element in the Series.
na_action
(optional): This parameter specifies what to do with missing values (NaNs). It can be one of 'ignore' (default), 'raise', or None.
Mapping Values Using a Dictionary:
import pandas as pd
data = {'A':['apple','banana','cherry','apple']}
df=pd.DataFrame(data)
fruit_to_color= {'apple':'red', 'banana':'yellow', 'cherry':'red'}
df['color']=df['A'].map(fruit_to_color)
This code maps fruit names in the ‘A’ column to their corresponding colors using a dictionary and creates a new ‘Color’ column in the DataFrame.
Mapping Values Using a Series:
import pandas as pd
data = {'A':['apple','banana','cherry','apple']}
df=pd.DataFrame(data)
color_series=pd.Series(['red','yellow','red'], index=['apple','banana','cherry'])…