Pandas DataFrame.pipe: Chain Function Calls on a DataFrame


Pandas DataFrame.pipe

The DataFrame.pipe method in pandas is used to chain function calls on a DataFrame. It allows you to pass a DataFrame through a sequence of functions, making code more readable and modular.


Syntax

The syntax for DataFrame.pipe is:

DataFrame.pipe(func, *args, **kwargs)

Here, DataFrame refers to the pandas DataFrame being passed through the function.


Parameters

ParameterDescription
funcThe function to apply to the DataFrame. This can be a built-in function, a lambda function, or a custom function.
*argsPositional arguments to pass to the function.
**kwargsKeyword arguments to pass to the function.

Returns

The result of applying the function to the DataFrame. This can be a DataFrame, Series, or any other object depending on the function.


Examples

Chaining Function Calls on a DataFrame

This example demonstrates how to use pipe to chain multiple function calls on a DataFrame.

Python Program

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Define a function to add a value to each element
def add_value(df, value):
    return df + value

# Define a function to multiply each element by a value
def multiply_value(df, value):
    return df * value

# Chain function calls using pipe
result = df.pipe(add_value, 10).pipe(multiply_value, 2)
print(result)

Output

    A   B
0  22  28
1  24  30
2  26  32

Using Pipe with Custom Functions

This example shows how to use pipe with custom functions to perform a series of operations on a DataFrame.

Python Program

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Define a function to filter rows
def filter_rows(df, threshold):
    return df[df['A'] > threshold]

# Define a function to reset the index
def reset_index(df):
    return df.reset_index(drop=True)

# Chain function calls using pipe
result = df.pipe(filter_rows, 1).pipe(reset_index)
print(result)

Output

   A  B
0  2  5
1  3  6

Using Pipe with Lambda Functions

This example demonstrates how to use pipe with lambda functions for quick, inline operations on a DataFrame.

Python Program

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Chain lambda functions using pipe
result = df.pipe(lambda x: x + 10).pipe(lambda x: x * 2)
print(result)

Output

    A   B
0  22  28
1  24  30
2  26  32

Summary

In this tutorial, we explored the DataFrame.pipe method in pandas. Key takeaways include:

  • Using pipe to chain function calls on a DataFrame.
  • Applying custom functions and lambda functions with pipe.
  • Improving code readability and modularity by chaining operations.

Python Libraries