Write a Python program to perform table-wise pipe function in a dataframe

PythonPandasServer Side ProgrammingProgramming

Assume, you have a dataframe and the result for table-wise function is,

Table wise function:
   Id  Mark
0  6.0 85.0
1  7.0 95.0
2  8.0 75.0
3  9.0 90.0
4 10.0 95.0

Solution

To solve this, we will follow the steps given below −

  • Define a dataframe

  • Create a user-defined function avg with two arguments and return the result as (a+b/2). It is defined below,

def avg(a,b):
   return (a+b/2)
  • Apply pipe() function to perform table-wise function inside first value as avg() and the second argument as 10 to calculate the avg of all the dataframe values.

df.pipe(avg,10)

Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.DataFrame({'Id':[1,2,3,4,5],'Mark':[80,90,70,85,90]})
print("DataFrame is:\n",df)
print("Table wise function:")
def avg(a,b):
   return (a+b/2)
print(df.pipe(avg,10))

Output

DataFrame is:
 Id Mark
0 1  80
1 2  90
2 3  70
3 4  85
4 5  90
Table wise function:
   Id  Mark
0  6.0 85.0
1  7.0 95.0
2  8.0 75.0
3  9.0 90.0
4 10.0 95.0
raja
Published on 12-Feb-2021 10:18:25
Advertisements