Bird
Raised Fist0
Pandasdata~10 mins

Arithmetic operations on columns in Pandas - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Arithmetic operations on columns
Start with DataFrame
↓
Select columns
↓
Apply arithmetic operation (+, -, *, /)
↓
Create new column or update existing
↓
Resulting DataFrame with updated columns
Start with a DataFrame, select columns, perform arithmetic operations, then store results in new or existing columns.
Execution Sample
Pandas
import pandas as pd

df = pd.DataFrame({'A': [10, 20, 30], 'B': [1, 2, 3]})
df['C'] = df['A'] + df['B']
print(df)
Adds columns 'A' and 'B' element-wise and stores the result in a new column 'C'.
Execution Table
StepActionColumns involvedOperationResulting 'C' column
1Create DataFrameA, BN/AN/A
2Select columns 'A' and 'B'A, BN/AN/A
3Add columns element-wiseA, BAddition[11, 22, 33]
4Assign result to new column 'C'CStore result[11, 22, 33]
5Print DataFrameA, B, CDisplayA: [10, 20, 30], B: [1, 2, 3], C: [11, 22, 33]
💡 All rows processed; arithmetic operation completed and stored in new column 'C'.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
df['A'][10, 20, 30][10, 20, 30][10, 20, 30][10, 20, 30]
df['B'][1, 2, 3][1, 2, 3][1, 2, 3][1, 2, 3]
df['C']N/AN/A[11, 22, 33][11, 22, 33]
Key Moments - 2 Insights
Why does df['C'] not exist before the operation but appears after?
Because df['C'] is created by assigning the result of df['A'] + df['B'] in step 4, as shown in the execution_table rows 3 and 4.
What happens if columns 'A' and 'B' have different lengths?
Pandas will raise an error or align by index, which can cause NaN values. This example assumes equal lengths as shown in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the result of adding columns 'A' and 'B'?
A[9, 18, 27]
B[10, 20, 30]
C[11, 22, 33]
D[1, 2, 3]
💡 Hint
Check the 'Resulting 'C' column' value in row 3 of the execution_table.
At which step is the new column 'C' created in the DataFrame?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Action' column in the execution_table where the result is assigned to 'C'.
If we changed the operation to df['C'] = df['A'] * df['B'], what would be the value of df['C'] after step 4?
A[10, 40, 90]
B[11, 22, 33]
C[9, 18, 27]
D[1, 2, 3]
💡 Hint
Multiply each element of 'A' by corresponding element of 'B' as in variable_tracker.
Concept Snapshot
Arithmetic operations on columns in pandas:
- Select columns by name (e.g., df['A'])
- Use operators (+, -, *, /) for element-wise operations
- Assign result to new or existing column (df['C'] = ...)
- Resulting column has same length as original columns
- Works best when columns have matching indexes
Full Transcript
This visual execution shows how to perform arithmetic operations on pandas DataFrame columns. We start with a DataFrame containing columns 'A' and 'B'. We select these columns and add them element-wise. The result is stored in a new column 'C'. The execution table traces each step, showing the creation of the DataFrame, selection of columns, the addition operation, and assignment to 'C'. The variable tracker shows how 'C' changes from non-existent to holding the sum values. Key moments clarify why 'C' appears only after assignment and what happens if column lengths differ. The quiz tests understanding of the addition result, the step when 'C' is created, and the effect of changing the operation to multiplication.

Practice

(1/5)
1. What does the expression df['total'] = df['price'] + df['tax'] do in pandas?
easy
A. Multiplies the 'price' and 'tax' columns and stores in 'total'.
B. Deletes the 'price' and 'tax' columns from the DataFrame.
C. Filters rows where 'price' plus 'tax' is greater than zero.
D. Creates a new column 'total' by adding 'price' and 'tax' columns element-wise.

Solution

  1. Step 1: Understand the operation on columns

    The expression adds values from 'price' and 'tax' columns for each row.
  2. Step 2: Assign result to new column

    The sum is stored in a new column named 'total' in the DataFrame.
  3. Final Answer:

    Creates a new column 'total' by adding 'price' and 'tax' columns element-wise. -> Option D
  4. Quick Check:

    Adding columns creates new column with sums [OK]
Hint: Adding columns creates a new column with their sums [OK]
Common Mistakes:
  • Thinking it multiplies instead of adds
  • Assuming it deletes columns
  • Confusing assignment with filtering
2. Which of the following is the correct syntax to subtract column 'B' from column 'A' in a pandas DataFrame df and store the result in a new column 'C'?
easy
A. df['C'] = df['A'] - df['B']
B. df['C'] = df['A'] + df['B']
C. df['C'] = df['A'] * df['B']
D. df['C'] = df['A'] / df['B']

Solution

  1. Step 1: Identify the subtraction operation

    We want to subtract column 'B' from 'A', so the operator is '-'.
  2. Step 2: Assign the result to new column 'C'

    Use df['C'] = df['A'] - df['B'] to store the difference.
  3. Final Answer:

    df['C'] = df['A'] - df['B'] -> Option A
  4. Quick Check:

    Subtraction uses '-' operator between columns [OK]
Hint: Use '-' operator between columns to subtract [OK]
Common Mistakes:
  • Using '+' instead of '-'
  • Using '*' or '/' operators incorrectly
  • Confusing column names or assignment
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({'A': [2, 4], 'B': [3, 5]})
df['C'] = df['A'] * df['B']
print(df['C'])

What is the output?
medium
A. [6, 20]
B. [5, 9]
C. [2, 4]
D. [3, 5]

Solution

  1. Step 1: Multiply columns 'A' and 'B' element-wise

    Row 0: 2 * 3 = 6, Row 1: 4 * 5 = 20.
  2. Step 2: Print the new column 'C'

    The output shows the values [6, 20] for the two rows.
  3. Final Answer:

    [6, 20] -> Option A
  4. Quick Check:

    Element-wise multiplication = [6, 20] [OK]
Hint: Multiply columns element-wise to get new column values [OK]
Common Mistakes:
  • Adding instead of multiplying
  • Printing wrong column
  • Confusing list output format
4. What is wrong with this code snippet?
df['D'] = df['A'] + '5'

Assuming 'A' is a numeric column.
medium
A. It will create a new column 'D' with all values as '5'.
B. It will add 5 to each value in column 'A' correctly.
C. It will raise a TypeError because you cannot add a string to a numeric column.
D. It will concatenate the string '5' to each numeric value in 'A'.

Solution

  1. Step 1: Check data types involved in addition

    Column 'A' is numeric, but '5' is a string, so adding them causes a type mismatch.
  2. Step 2: Understand pandas behavior on mixed types

    Pandas cannot add string to numeric directly, so it raises a TypeError.
  3. Final Answer:

    It will raise a TypeError because you cannot add a string to a numeric column. -> Option C
  4. Quick Check:

    Adding string to number causes TypeError [OK]
Hint: Check data types before arithmetic to avoid errors [OK]
Common Mistakes:
  • Assuming string '5' is converted automatically
  • Expecting concatenation with numbers
  • Ignoring error messages
5. You have a DataFrame df with columns 'cost' and 'discount'. You want to create a new column 'final_price' that subtracts the discount from cost and then applies a 10% tax on the result. Which code correctly does this?
hard
A. df['final_price'] = df['cost'] * 1.10 - df['discount']
B. df['final_price'] = (df['cost'] - df['discount']) * 1.10
C. df['final_price'] = df['cost'] - (df['discount'] * 1.10)
D. df['final_price'] = df['cost'] - df['discount'] * 1.10

Solution

  1. Step 1: Subtract discount from cost

    Calculate the price after discount: df['cost'] - df['discount'].
  2. Step 2: Apply 10% tax on discounted price

    Multiply the result by 1.10 to add 10% tax.
  3. Step 3: Assign to 'final_price'

    Store the final value in the new column 'final_price'.
  4. Final Answer:

    df['final_price'] = (df['cost'] - df['discount']) * 1.10 -> Option B
  5. Quick Check:

    Subtract then multiply for tax = correct formula [OK]
Hint: Use parentheses to control order: subtract first, then multiply [OK]
Common Mistakes:
  • Missing parentheses causing wrong order
  • Multiplying discount instead of discounted price
  • Applying tax before subtracting discount
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard