Python | Pandas Series.clip()

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Python Series.clip() is used to clip value below and above to passed Least and Max value. This method comes in use when doing operations like Signal processing. As we know there are only two values in Digital signal, either High or Low. Pandas Series.clip() can be used to restrict the value to a Specific Range.

Syntax: Series.clip(lower=None, upper=None, axis=None, inplace=False)



Parameters:
lower: Sets Least value of range. Any values below this are made equal to lower.
upper: Sets Max value of range. Any values above this are made equal to upper.
axis: 0 or ‘index’ to apply method by rows and 1 or ‘columns’ to apply by columns
inplace: Make changes in the caller series itself. (Overwrite with new values)

Return type: Series with updated values

To download the data set used in following example, click here.
In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.

Example
In this example, the .clip() method is called on Age column of data. A minimum value of 22 is passed to lower parameter and 25 to upper parameter. The returned series is then stored in a new column ‘New Age’. Before doing any operations, Null rows were dropped using .dropna() to avoid errors.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas module 
import pandas as pd 
  
# importing regex module
import re
    
# making data frame 
    
# removing null values to avoid errors 
data.dropna(inplace = True
  
# lower value of range
lower = 22
  
# upper value of range
upper = 25
  
# passing values to new column
data["New Age"]= data["Age"].clip(lower = lower, upper = upper)
  
# display
data

chevron_right


Output:
As shown in the output image, the New Age column has least value of 22 and max value of 25. All values are restricted to this range. Values below 22 were made equal to 22 and values above 25 were made equal to 25.



My Personal Notes arrow_drop_up

Developer in day, Designer at night GSoC 2019 with Python Software Foundation (EOS Design system)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.