Pandas DataFrame pipe() Method
If we want to apply a method to the whole DataFrame, we can use the Python pandas DataFrame.pipe()
method. This method applies the specified method or multiple methods(chain) to all rows and columns of the DataFrame in the FIFO(First in First out) manner. The applying method can be a user-defined method or it can also be a built-in method.
The below shows the syntax of the DataFrame.pipe()
method.
Syntax
DataFrame.pipe(func, *args, **kwargs)
Parameters
func: It is the method to apply to the specified DataFrame.
args: It can be iterable, which is optional. It indicates the positional arguments passed into func
.
kwargs: It indicates mapping, which is optional. A dictionary of keyword arguments passed into func
.
Example 1: Apply a user-defined method to the DataFrame
Let's create a DataFrame and apply a DataFrame.pipe()
method to the DataFrame. Here, in this example, we defined a method called add()
which adds '1'
to the element. Using the DataFrame.pipe()
method we can apply this add()
method to the entire DataFrame. See the below example.
#importing pandas as pd
import pandas as pd
def add(x):
return x+1
df=pd.DataFrame({'A':[1,2,3],'B':[4,5,6],'C':[7,8,9]})
print("--------The DataFrame is------")
print(df)
print("---------------------")
print(df.pipe(add))
--------The DataFrame is------
A B C
0 1 4 7
1 2 5 8
2 3 6 9
---------------------
A B C
0 2 5 8
1 3 6 9
2 4 7 10
Example 2: Apply a user-defined method to the DataFrame
Let's create a DataFrame and apply a DataFrame.pipe()
method to the DataFrame. Here, in this example, we apply the np.add()
method to the entire DataFrame using the DataFrame.pipe()
method. See the below example.
#importing pandas as pd
import pandas as pd
#importing numpy as np
import numpy as np
df=pd.DataFrame({'A':[1,1,1],'B':[2,2,2],'C':[3,3,3]})
print("--------The DataFrame is------")
print(df)
print("---------------------")
print(df.pipe(np.add,2))
--------The DataFrame is------
A B C
0 1 2 3
1 1 2 3
2 1 2 3
---------------------
A B C
0 3 4 5
1 3 4 5
2 3 4 5
Example 3: Apply a user-defined method to the DataFrame
We can apply multiple methods to the DataFrame using the DataFrame.pipe()
method. See the below example.
In the example, we are adding the value '2'
to the DataFrame and multiplying the resultant DataFrame by '2'
consecutively using the np.add()
and np.multiply()
methods respectively.
#importing pandas as pd
import pandas as pd
#importing numpy as np
import numpy as np
df=pd.DataFrame({'A':[1,1,1],'B':[2,2,2],'C':[3,3,3]})
print("--------The DataFrame is------")
print(df)
print("---------------------")
print(df.pipe(np.add,2).pipe(np.multiply,2))
--------The DataFrame is------
A B C
0 1 2 3
1 1 2 3
2 1 2 3
---------------------
A B C
0 6 8 10
1 6 8 10
2 6 8 10
Conclusion
In this tutorial, we learned the Python pandas DataFrame.pipe()
method. We learned the syntax, parameters and applied this method on the DataFrame.