- API reference
- DataFrame
- pandas.DataFrame.map
pandas.DataFrame.map#
- DataFrame.map(func,na_action=None,**kwargs)[source]#
Apply a function to a Dataframe elementwise.
Added in version 2.1.0:DataFrame.applymap was deprecated and renamed to DataFrame.map.
This method applies a function that accepts and returns a scalarto every element of a DataFrame.
- Parameters:
- funccallable
Python function, returns a single value from a single value.
- na_action{None, ‘ignore’}, default None
If ‘ignore’, propagate NaN values, without passing them to func.
- **kwargs
Additional keyword arguments to pass as keywords arguments tofunc.
- Returns:
- DataFrame
Transformed DataFrame.
See also
DataFrame.apply
Apply a function along input axis of DataFrame.
DataFrame.replace
Replace values given into_replace withvalue.
Series.map
Apply a function elementwise on a Series.
Examples
>>>df=pd.DataFrame([[1,2.12],[3.356,4.567]])>>>df 0 10 1.000 2.1201 3.356 4.567
>>>df.map(lambdax:len(str(x))) 0 10 3 41 5 5
Like Series.map, NA values can be ignored:
>>>df_copy=df.copy()>>>df_copy.iloc[0,0]=pd.NA>>>df_copy.map(lambdax:len(str(x)),na_action='ignore') 0 10 NaN 41 5.0 5
It is also possible to usemap with functions that are notlambda functions:
>>>df.map(round,ndigits=1) 0 10 1.0 2.11 3.4 4.6
Note that a vectorized version offunc often exists, which willbe much faster. You could square each number elementwise.
>>>df.map(lambdax:x**2) 0 10 1.000000 4.4944001 11.262736 20.857489
But it’s better to avoid map in that case.
>>>df**2 0 10 1.000000 4.4944001 11.262736 20.857489