Pandas DataFrame | add method
Start your free 7-days trial now!
Pandas DataFrame.add(~)
method computes the sum of the values in the source DataFrame and another scalar, sequence Series or DataFrame, that is:
DataFrame + other
Unless you use the parameters axis
, level
and fill_value
, add(~)
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 the source DataFrame and other
.
2. axis
link | 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 does not align with that of other
. 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 computation of the sum. If the sum involves two NaN
, then the result would 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":[4,5]})df_other = pd.DataFrame({"A":[6,7], "B":[8,9]})
A B | A B0 2 4 | 0 6 81 3 5 | 1 7 9
Computing their sum:
df.add(df_other)
A B0 8 121 10 14
Note that this equivalent to:
df + df_other
A B0 8 121 10 14
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.add([10,20]) # axis=1
A B0 12 241 13 25
Here, we're doing the following element-wise addition:
2+10 4+203+10 5+20
Column-wise addition
To broadcast other
for each column in df
, set axis=0
like so:
df.add([10,20], axis=0)
A B0 12 141 23 25
Here, we're doing the following element-wise addition:
2+10 4+103+20 5+20
Specifying fill_value
Consider the following DataFrames with some missing values:
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 add(~)
, any operation with NaN
results in NaN
:
df.add(df_other)
A B0 12.0 NaN1 NaN NaN
We can fill the NaN
values before we compute the sum using fill_value
:
df.add(df_other, fill_value=100)
A B0 12.0 NaN1 120.0 105.0
Here, notice when the addition involves NaN
, the resulting sum is still NaN
, regardless of fill_value
.