The DataFrame.add()
method in Python is used to perform element-wise addition between DataFrame and
Note: The arithmetic+
operator can also be used for addition. However, it does not provide a facility to deal withNaN
values and other objects.
DataFrame.add(other, axis='columns', level=None, fill_value=None)
The DataFrame.add()
method takes the following argument values:
other
: This parameter value can either be a DataFrame, array-like, series, or scalar.axis
: The default value of this parameter value is 'columns'
.1 or 'columns'
(this represents DataFrames).0 or 'index'
(this represents series). level
: The default value of this parameter value is None
. The broadcast value across a level can be either int
or None
. fill_value
: The default value of this parameter value is None
. It can either be a float
value or None
, both of which help to fill empty NaN
fields.This method returns a Pandas DataFrame.
We can use this function in multiple ways. Here is a list of some scenarios where we can use this function:
In this program, we are going to discuss all the scenarios mentioned above.
# importing Pandas and Numpyimport pandas as pdimport numpy as np# Creating a DataFramedf1= pd.DataFrame([[5, 3, 6, 4],[11, None, 4, 3],[4, 3, 8, None],[5, 4, 2, 8]])# Creating another DataFramedf2= pd.DataFrame([[None, 4, 5, 9],[1, None, 4, 3],[14, 3, -1, None],[2, 14, 8, 8]])# Creating Numpy arraydata = np.array([1, 2, 3, 4])# Converting to Python seriesseries = pd.Series(data)"""DataFrame and Constant"""# Invoking add() method# Evaluating addition between df1 and constantaddition= df1.add(3, fill_value = 2)# print resultsprint("DataFrame and Constant")print(addition)"""Both are DataFrames"""# Evaluating addition between df1 and df2addition= df1.add(df2, fill_value = 2)print("\nBoth are DataFrames")print(addition)"""DataFrame and Series"""# Evaluating addition between df1 and seriesaddition= df1.add(series)print("\nDataFrame and Series")print(addition)
df1
. It has 16 entries, that is, four rows and four columns.df2
. It also has four rows and four columns.df1.add(3, fill_value=2)
function with DataFrame df1
as the self
object and the constant value 3
as an argument. This results in element-wise addition. fill_value = 2
replaces the NaN
values with 2
.df1.add(df2)
function with DataFrame as the self
object and DataFrame as an argument. This results in element-wise addition. fill_value = 2
replaces all the NaN
values with 2.df1.add(series)
function with DataFrame as the self
object and the series
object as an argument.