- API reference
- Series
- pandas.Series.apply
pandas.Series.apply#
- Series.apply(func,convert_dtype=<no_default>,args=(),*,by_row='compat',**kwargs)[source]#
Invoke function on values of Series.
Can be ufunc (a NumPy function that applies to the entire Series)or a Python function that only works on single values.
- Parameters:
- funcfunction
Python function or NumPy ufunc to apply.
- convert_dtypebool, default True
Try to find better dtype for elementwise function results. IfFalse, leave as dtype=object. Note that the dtype is alwayspreserved for some extension array dtypes, such as Categorical.
Deprecated since version 2.1.0:
convert_dtypehas been deprecated. Doser.astype(object).apply()instead if you wantconvert_dtype=False.- argstuple
Positional arguments passed to func after the series value.
- by_rowFalse or “compat”, default “compat”
If
"compat"and func is a callable, func will be passed each element ofthe Series, likeSeries.map. If func is a list or dict ofcallables, will first try to translate each func into pandas methods. Ifthat doesn’t work, will try call to apply again withby_row="compat"and if that fails, will call apply again withby_row=False(backward compatible).If False, the func will be passed the whole Series at once.by_rowhas no effect whenfuncis a string.Added in version 2.1.0.
- **kwargs
Additional keyword arguments passed to func.
- Returns:
- Series or DataFrame
If func returns a Series object the result will be a DataFrame.
See also
Series.mapFor element-wise operations.
Series.aggOnly perform aggregating type operations.
Series.transformOnly perform transforming type operations.
Notes
Functions that mutate the passed object can produce unexpectedbehavior or errors and are not supported. SeeMutating with User Defined Function (UDF) methodsfor more details.
Examples
Create a series with typical summer temperatures for each city.
>>>s=pd.Series([20,21,12],...index=['London','New York','Helsinki'])>>>sLondon 20New York 21Helsinki 12dtype: int64
Square the values by defining a function and passing it as anargument to
apply().>>>defsquare(x):...returnx**2>>>s.apply(square)London 400New York 441Helsinki 144dtype: int64
Square the values by passing an anonymous function as anargument to
apply().>>>s.apply(lambdax:x**2)London 400New York 441Helsinki 144dtype: int64
Define a custom function that needs additional positionalarguments and pass these additional arguments using the
argskeyword.>>>defsubtract_custom_value(x,custom_value):...returnx-custom_value
>>>s.apply(subtract_custom_value,args=(5,))London 15New York 16Helsinki 7dtype: int64
Define a custom function that takes keyword argumentsand pass these arguments to
apply.>>>defadd_custom_values(x,**kwargs):...formonthinkwargs:...x+=kwargs[month]...returnx
>>>s.apply(add_custom_values,june=30,july=20,august=25)London 95New York 96Helsinki 87dtype: int64
Use a function from the Numpy library.
>>>s.apply(np.log)London 2.995732New York 3.044522Helsinki 2.484907dtype: float64