Pandas DataFrame | rsub method
Start your free 7-days trial now!
Pandas DataFrame.rsub(~) method subtracts the values in the source DataFrame from a scalar, sequence, Series or DataFrame, that is:
other - DataFrame
As a side note, this is just the reverse of DataFrame.sub(~):
DataFrame - other
Unless you use the parameters axis, level and fill_value, rsub(~) is equivalent to performing subtraction using the - operator.
Parameters
1. otherlink | scalar or sequence or Series or DataFrame
The resulting DataFrame will be the source DataFrame subtracted from other.
2. axislink | int or string | optional
Whether to broadcast other for each column or row of the source DataFrame:
Axis | Description |
|---|---|
|
|
|
|
This is only relevant if the shape of the source DataFrame and that of other does not align. By default, axis=1.
3. level | int or string | optional
The name or the integer index of the level to consider. This is relevant only if your DataFrame is Multi-index.
4. fill_valuelink | float or None | optional
The value to replace NaN before the computation. Subtraction between two NaN will always result in NaN. By default, fill_value=None.
Return Value
A new DataFrame resulting from the subtraction.
Examples
Basic usage
Consider the following DataFrames:
df = pd.DataFrame({"A":[1,10], "B":[100,1000]})df_other = pd.DataFrame({"A":[3,4],"B":[5,6]})
A B | A B0 1 100 | 0 3 51 10 1000 | 1 4 6
Subtracting df from df_other yields:
df.rsub(df_other)
A B0 2 -951 -6 -994
Broadcasting
Consider the following DataFrame:
df = pd.DataFrame({"A":[1,10], "B":[100,1000]})df
A B0 1 1001 10 1000
Row-wise subtraction
By default, axis=1, which means that other will be broadcasted for each row in df:
df.rsub([3,4]) # axis=1
A B0 2 -961 -7 -996
Here, we're doing the following element-wise subtraction:
3-1 4-1003-10 4-1000
Column-wise subtraction
To broadcast other for each column in df, set axis=0 like so:
df.rsub([3,4], axis=0)
A B0 2 -971 -6 -996
Here, we're doing the following element-wise subtraction:
3-1 3-1004-10 4-1000
Specifying fill_value
Consider the following DataFrames with some missing values:
df = pd.DataFrame({"A":[3,np.NaN], "B":[np.NaN,4]})df_other = pd.DataFrame({"A":[10,100],"B":[np.NaN,np.NaN]})
A B | A B0 3.0 NaN | 0 10 NaN1 NaN 4.0 | 1 100 NaN
By default, when we perform subtraction using rsub(~), any operation with NaN results in NaN:
df.rsub(df_other)
A B0 7.0 NaN1 NaN NaN
We can fill the NaN values before we perform subtraction by using the fill_value parameter like so:
df.rsub(df_other, fill_value=100)
A B0 7.0 NaN1 0.0 96.0
Here, notice how the subtraction between two NaN will still result in a NaN regardless of fill_value.