Write a Python program to trim the minimum and maximum threshold value in a dataframe

PythonPandasServer Side ProgrammingProgramming

Assume, you have a dataframe and the result for trim of minimum and the maximum threshold value,

minimum threshold:
   Column1 Column2
0    30    30
1    34    30
2    56    30
3    78    50
4    30    90
maximum threshold:
   Column1 Column2
0    12    23
1    34    30
2    50    25
3    50    50
4    28    50
clipped dataframe is:
   Column1 Column2
0    30    30
1    34    30
2    50    30
3    50    50
4    30    50

Solution

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

  • Define a dataframe

  • Apply df.clip function inside (lower=30) to calculate minimum threshold value,

df.clip(lower=30)
  • Apply df.clip function inside (upper=50) to calculate maximum threshold value

df.clip(upper=50)
  • Apply clipped dataframe with min and max threshold limit as,

df.clip(lower=30,upper=50)

Example

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

import pandas as pd
data = {"Column1":[12,34,56,78,28],
         "Column2":[23,30,25,50,90]}
df = pd.DataFrame(data)
print("DataFrame is:\n",df)
print("minimum threshold:\n",df.clip(lower=30))
print("maximum threshold:\n",df.clip(upper=50))
print("clipped dataframe is:\n",df.clip(lower=30,upper=50))

Output

DataFrame is:
   Column1 Column2
0    12    23
1    34    30
2    56    25
3    78    50
4    28    90
minimum threshold:
   Column1 Column2
0    30    30
1    34    30
2    56    30
3    78    50
4    30    90
maximum threshold:
   Column1 Column2
0    12    23
1    34    30
2    50    25
3    50    50
4    28    50
clipped dataframe is:
   Column1 Column2
0    30    30
1    34    30
2    50    30
3    50    50
4    30    50
raja
Published on 11-Feb-2021 11:33:59

Advertisements