Pandas DataFrame clip() Method – Be on the Right Side of Change (original) (raw)

Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd import numpy as np


The clip() method assigns values outside the boundary to boundary values. Thresholds can be singular values or array-like, and in the latter case, the clipping is performed element-wise in the specified axis.

The syntax for this method is as follows:

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

Parameter Description
lower This parameter is the minimum threshold value. By default, the value is None.
upper This parameter is the maximum threshold value. By default, the value is None.
axis If zero (0) or index is selected, apply to each column. Default 0.If one (1) apply to each row.
inplace This parameter aligns the object with lower and upper along the specified axis.
*args
**kwargs Additional keywords have no effect.

For this example, Rivers Clothing is having a sale on Pants in sizes Medium and Large. Unfortunately, these prices are greater than the sale price of $25.00 and need to be modified.

df_prices = pd.DataFrame({'Tops': [10.22, 12.45, 17.45], 'Tanks': [9.99, 10.99, 11.99], 'Pants': [24.95, 26.95, 32.95], 'Sweats': [18.99, 19.99, 21.99]})

index_ = ['Small', 'Medium', 'Large'] df_prices.index = index_

result = df_inv.clip(10, 25, axis='rows') print(result)

Output

| | Tops | Tanks | Pants | Sweats | | | ------ | ----- | ----- | --------- | ----- | | Small | 10.22 | 10.00 | 24.95 | 18.99 | | Medium | 12.45 | 10.99 | 25.00 | 19.99 | | Large | 17.45 | 11.99 | 25.00 | 21.99 |

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.