Pandas DataFrame | radd method
Start your free 7-days trial now!
Pandas DataFrame.radd(~)
method computes and returns the sum of a scalar, sequence, Series or DataFrame and the values in the source DataFrame, that is:
other + DataFrame
Note that this is the reverse of DataFrame.add(~)
, which does the following:
DataFrame + other
Unless you use the parameters axis
, level
and fill_value
, radd(~)
is equivalent to performing addition using the +
operator.
Parameters
1. other
link | scalar
or sequence
or Series
or DataFrame
The resulting DataFrame will be the sum of other
and the source DataFrame.
2. axis
link | int
or string
| optional
Whether to broadcast other
for each column or row of the source DataFrame:
Axis | Description |
---|---|
|
|
|
|
This is relevant only when the shape of the source DataFrame and 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_value
link | float
or None
| optional
The value to replace NaN
before the computing the sum. If both the pair-wise entries in the source DataFrame and other
are NaN
, then the resulting sum will still be NaN
. By default, fill_value=None
.
Return Value
A new DataFrame
computed by the sum of the source DataFrame and other
.
Examples
Basic usage
Consider the following DataFrames:
df = pd.DataFrame({"A":[2,3], "B":["a","b"]})df_other = pd.DataFrame({"A":[6,7], "B":["c","d"]})
A B | A B0 2 a | 0 6 c1 3 b | 1 7 d
Taking the sum yields:
df.radd(df_other)
A B0 8 ca1 10 db
Broadcasting
Consider the following DataFrame:
df = pd.DataFrame({"A":[2,3], "B":[4,5]})df
A B0 2 41 3 5
Row-wise addition
By default, axis=1
, which means that other
will be broadcasted for each row in df
:
df.radd([10,20]) # axis=1
A B0 12 241 13 25
Here, we're doing the following element-wise addition:
10+2 20+410+3 20+5
Column-wise addition
To broadcast other
for each column in df
, set axis=0
like so:
df.radd([10,20], axis=0)
A B0 12 141 23 25
Here, we're doing the following element-wise addition:
10+2 10+420+3 20+5
Specifying fill_value
Consider the following DataFrames:
df = pd.DataFrame({"A":[2,np.NaN], "B":[np.NaN,5]})df_other = pd.DataFrame({"A":[10, 20],"B":[np.NaN,np.NaN]})
A B | A B0 2 NaN | 0 10 NaN1 NaN 5 | 1 20 NaN
By default, when we take the sum using radd(~)
, any operation with NaN
results in NaN
:
df.radd(df_other)
A B0 2.0 NaN1 NaN NaN
We can fill the NaN
values before we compute the sum by using the fill_value
parameter:
df.radd(df_other, fill_value=100)
A B0 12.0 NaN1 120.0 105.0
Notice when the addition is between two NaN
, the resulting sum would still be a NaN
regardless of fill_value
.