Pandas DataFrame | pipe method
Start your free 7-days trial now!
Pandas DataFrame.pipe(~) method applies a specified function on the source DataFrame. This is not done in-place, meaning the source DataFrame is left intact and a new DataFrame is returned.
Parameters
1. func | function
The function to apply on the source DataFrame.
2. args | iterable | optional
The positional arguments to pass to func.
3. kwargs | mapping | optional
The keyword arguments to pass to func.
Return Value
A new DataFrame.
Examples
Basic usage
Consider the following DataFrame:
df = pd.DataFrame({"A":[3,4],"B":[5,6]})df
A B0 3 51 4 6
Suppose we wanted to add 10 to each entry:
def add_ten(x): # x is a DataFrame (df) return x + 10
df.pipe(add_ten)
A B0 13 151 14 16
Here, a new DataFrame is created and our original df is left intact.
Method chaining
What's nice about pipe(~) is that we can make a chain:
def add_ten(x): return x + 10
df = pd.DataFrame({"A":[3,4],"B":[5,6]})df.pipe(add_ten).pipe(add_ten)
A B0 23 251 24 26
Specifying positional arguments
We can pass in positional arguments for our func:
def add(x, y, z): return x + y + z
df = pd.DataFrame({"A":[3,4],"B":[5,6]})df.pipe(add, 4, 6)
A B0 13 151 14 16
Here, the arguments of add are as follows:
xis the source DataFrame (df)yis assigned a value of4zis assigned a value of6
Specifying keyword arguments
We can pass in keyword arguments for our func like so:
def add(x, y, k): return x + y + k
df = pd.DataFrame({"A":[3,4],"B":[5,6]})df.pipe(add, 4, k=6)
A B0 13 151 14 16