w3resource

Pandas DataFrame: apply() function

DataFrame - apply() function

The apply() function is used to apply a function along an axis of the DataFrame.

Objects passed to the function are Series objects whose index is either the DataFrame’s index (axis=0) or the DataFrame’s columns (axis=1).

By default (result_type=None), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument.

Syntax:

DataFrame.apply(self, func, axis=0, broadcast=None, raw=False, reduce=None, result_type=None, args=(), **kwds)

Parameters:

Name Description Type/Default Value Required / Optional
func                   Function to apply to each column or row. function Required
axis  

Axis along which the function is applied:

  • 0 or ‘index’: apply function to each column.
  • 1 or ‘columns’: apply function to each row.
 {0 or ‘index’, 1 or ‘columns’}
Default Value: 0
Required
raw   
  • False : passes each row or column as a Series to the function.
  • True : the passed function will receive ndarray objects instead. If you are just applying a NumPy reduction function this will achieve much better performance.
bool
Default Value: False
Required
result_type   These only act when axis=1 (columns):
  • ‘expand’ : list-like results will be turned into columns.
  • 'reduce' : returns a Series if possible rather than expanding list-like results. This is the opposite of ‘expand’.
  • 'broadcast' : results will be broadcast to the original shape of the DataFrame, the original index and columns will be retained.

The default behaviour (None) depends on the return value of the applied function: list-like results will be returned as a Series of those. However if the apply function returns a Series these are expanded to columns.

{'expand', 'reduce', 'broadcast', None}
Default Value: None
Required
args  Positional arguments to pass to func in addition to the array/series. tuple Required
**kwds

Additional keyword arguments to pass as keywords arguments to func.   Required

Returns: Series or DataFrame
Result of applying func along the given axis of the DataFrame.

Example:


Download the above Notebook from here.

Previous: DataFrame - combine_first() function
Next: DataFrame - applymap() function