How To Apply Function To A DataFrame?


How To Apply Function To A DataFrame?

Table Of Contents:

  1. Syntax ‘apply( )’ Method In Pandas.
  2. Examples ‘apply( )’ Method.

(1) Syntax:

DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwargs)

Description:

  • Apply a function along an axis of the DataFrame.

Parameters:

  • func: function- Function to apply to each column or row.
  • axis{0 or ‘index’, 1 or ‘columns’}, default 0 –

    Axis along which the function is applied:

    • 0 or ‘index’: apply the function to each column.

    • 1 or ‘columns’: apply the function to each row.

  • rawbool, default False –

    Determines if row or column is passed as a Series or ndarray object:

    • 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.

  • result_type{‘expand’, ‘reduce’, ‘broadcast’, None}, default None –

    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.

  • args: tuple – Positional arguments to pass to func in addition to the array/series.
  • **kwargs Additional keyword arguments to pass as keywords arguments to func.

Returns:

  • Series or DataFrame – Result of applying func along the given axis of the DataFrame.

(2) Examples Of apply() Method:

Example-1

df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B'])
df

Output:

# Applying Square Root Function To Each Column.

df.apply(np.sqrt)

Output:

# Using a reducing function on either axis:

df.apply(np.sum, axis=0)

Output:

A    12
B    27
dtype: int64
df.apply(np.sum, axis=1)

Output:

df.apply(np.sum, axis=1)

# Returning a list-like will result in a Series

df.apply(lambda x: [1, 2], axis=1)

Output:

0    [1, 2]
1    [1, 2]
2    [1, 2]
dtype: object

# Passing result_type=’expand’ will expand list-like results to columns of a Dataframe

df.apply(lambda x: [1, 2], axis=1, result_type='expand')

Output:

# Returning a Series inside the function is similar to passing result_type=’expand’. The resulting column names will be the Series index.

df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1)

Output:

# Passing result_type=’broadcast’ will ensure the same shape result, whether list-like or scalar is returned by the function, and broadcast it along the axis. The resulting column names will be the originals.

df.apply(lambda x: [1, 2], axis=1, result_type='broadcast')

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *