import pandas as pd
df = pd.DataFrame({'MATH': [30, 40], 'ENGLISH': [20, 30]})
print(df.add(5))
Expected Output:
MATH ENGLISH
0 35 25
1 45 35
The DataFrame.add() method executes element-wise addition between DataFrames, Series, or scalar quantities. Unlike the standard Python + operator, add() provides key parameters like fill_value to manage missing data gracefully during index alignment.
DataFrame.add(other, axis='columns', level=None, fill_value=None)other: Scalar, Series, or DataFrame to add.axis: 0 or 'index' (align by row indices), 1 or 'columns' (align by column names).fill_value: Substitute value for missing entries prior to addition.Adding a constant scalar value across selected numerical columns updates every entry by the specified amount.
import pandas as pd
df_scores = pd.DataFrame({
'MATH': [75, 82, 90],
'SCIENCE': [68, 74, 88]
})
# Add 5 grace marks to all columns
df_bonus = df_scores.add(5)
print(df_bonus)
When adding a Series to a DataFrame, use axis=1 to align Series indices with DataFrame columns, or axis=0 to align with DataFrame row indices.
import pandas as pd
df_marks = pd.DataFrame({
'MATH': [70, 80],
'ENGLISH': [60, 65]
}, index=['Ravi', 'Raju'])
subject_bonus = pd.Series({'MATH': 10, 'ENGLISH': 5})
# Column-aligned addition (axis=1)
df_result = df_marks.add(subject_bonus, axis=1)
print(df_result)
Combining DataFrames with non-overlapping row or column labels yields NaN entries with standard addition. Passing fill_value=0 substitutes missing entries before performing the addition.
import pandas as pd
df1 = pd.DataFrame({'Q1_SALES': [100, 200]}, index=['Store_A', 'Store_B'])
df2 = pd.DataFrame({'Q1_SALES': [300, 400]}, index=['Store_B', 'Store_C'])
# Consolidate sales figures safely
df_total = df1.add(df2, fill_value=0)
print(df_total)
Expected Output:
Q1_SALES
Store_A 100.0
Store_B 500.0
Store_C 400.0
Q: How does add() differ from the + operator?
The add() method allows explicit parameters like fill_value and axis, whereas + performs default label alignment and introduces NaN values for mismatched indices.
Q: What happens if both DataFrames have missing values at the same index?
If both values are missing (NaN), fill_value fills one operand, resulting in a valid sum rather than NaN.
level=0.
Explore interactive code cells, dynamically generate classes, test type vs isinstance comparisons, and run self-validating assertions.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.