Pandas DataFrame | clip method
Start your free 7-days trial now!
Pandas DataFrame.clip(~)
method is used to ensure that the values of the DataFrame are between a particular range.
Parameters
1. lower
link | scalar
or array_like
| optional
The lower bound to clip. Values that are smaller than lower
will be replaced by lower
. You can ignore the lower bound by passing in None
.
2. upper
link | scalar
or array_like
| optional
The upper bound to clip. Values that are larger than upper
will be replaced by upper
. You can ignore the upper bound by passing in None
.
3. axis
link | int
or string
| optional
Whether to perform clipping to each row or each column:
Axis | Description |
---|---|
| Clip entire DataFrame. |
| Clip element-wise for each column. |
| Clip element-wise for each row. |
By default, axis=None
. When you pass in an array for either lower
or upper
, you should set axis
to either 0
or 1
depending on your needs. See examples below for clarification.
4. inplace
| boolean
| optional
Whether or not to directly modify the source DataFrame without creating a new one. By default, inplace=False
, that is, a new DataFrame will be returned and the source DataFrame will be kept intact.
Return Value
A DataFrame
with its values clipped.
Examples
Basic usage
Consider the following DataFrame:
df
A B0 2 61 4 8
Clipping with lower and upper bounds set to 3
and 6
respectively:
df.clip(lower=3, upper=6)
A B0 3 61 4 6
Here, note the following:
any value in the DataFrame that is smaller than
3
will be replaced by the value3
.any value that is larger than
6
will be replaced by the value6
.at the end, the lowest value in the DataFrame should be
3
, and the largest should be6
.
Passing in an array
Clipping each column
Consider the same DataFrame as above:
df
A B0 2 61 4 8
We can pass in an array of bounds, like so:
df.clip(lower=[5,2], axis=0)
A B0 5 61 4 8
Here, since axis=0
, we are clipping each column element-wise. To break down what's happening:
Column A: [5 2] lower clips [2 4] = [5 4]Column B: [5 2] lower clips [6 8] = [6 8]
We could also set a combination of an array and a number like so:
df.clip(lower=[5,2], upper=6, axis=0)
A B0 5 61 4 6
To break down what's happening:
Column A: [5 2] lower clips [2 4] = [5 4] -> upper clipped to [5 4]Column B: [5 2] lower clips [6 8] = [6 8] -> upper clipped to [6 6]
Clipping each row
Here's df
again for your reference:
df
A B0 2 61 4 8
Setting axis=1
clips each row element-wise:
df.clip(lower=[5,2], upper=6, axis=1)
A B0 5 61 5 6
Again, here's the break down:
Column One: [5 2] lower clips [2 6] = [5 6] -> upper clipped to [5 6]Column Two: [5 2] lower clips [4 8] = [5 8] -> upper clipped to [5 6]