Pandas DataFrame clip() method with examples

Spread the love

Pandas dataframe.clip() method is used to trim values at specified input threshold. We can use this function to put a lower limit and upper limit on the values that any cell can have in the dataframe.

Syntax –

DataFrame.clip(lower=None, upper=None, axis=None, inplace=False, *args, **kwargs)

lower – Minimum threshold value. All values below this threshold will be set to it. A missing threshold (e.g NA) will not clip the value.

upper – Maximum threshold value. All values above this threshold will be set to it. A missing threshold (e.g NA) will not clip the value.

axis – Align object with lower and upper along the given axis.

inplace – Whether to perform the operation in place on the data.

*args **kwargs – Additional keywords have no effect but might be accepted for compatibility with numpy.

Examples –

Let’s create a dataframe to work with

import pandas as pd

data = {'Apple':[89, 89, 90, 110, 125, 84, 131, 123, 123, 140, 145, 145],
       'Orange': [46, 46, 50, 65, 63, 48, 110, 120, 60, 42, 47, 62],
       'Banana': [26, 30, 30, 25, 38, 22, 22, 36, 20, 27, 23, 34 ],
       'Mango': [80, 80, 90, 125, 130, 150, 140, 140, 135, 135, 80, 90]}

index = ['Jan','Feb','Mar','Apr','May','June','Jul','Aug','Sep','Oct','Nov','Dec']
df = pd.DataFrame(data, index=index)
df

This dataframe contains values between 20 to 150.

Now, Let’s say that you want to trim or limit the values between 50 and 100 i.e. all the values lower than 50 will be set to 50 and all the values greater than 100 will be set to 100 and all the other values will be left unchanged.

To do that we can use the clip() method in pandas.

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

Rating: 1 out of 5.

Leave a Reply