Arithmetic operations on columns in Pandas - Time & Space Complexity
We want to understand how the time to do arithmetic on columns changes as the data grows.
How does the work increase when we have more rows in the table?
Analyze the time complexity of the following code snippet.
import pandas as pd
n = 10 # Example value for n
df = pd.DataFrame({
'A': range(n),
'B': range(n, 2*n)
})
df['C'] = df['A'] + df['B']
This code creates two columns with numbers and adds them to make a new column.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each pair of numbers from columns A and B.
- How many times: Once for each row in the DataFrame.
As the number of rows grows, the number of additions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to add columns grows in a straight line as the data gets bigger.
[X] Wrong: "Adding two columns is instant no matter how big the data is."
[OK] Correct: Each row needs one addition, so more rows mean more work and more time.
Knowing how operations grow with data size helps you explain your code choices clearly and confidently.
"What if we added two columns but only for rows where a condition is true? How would the time complexity change?"
Practice
df['total'] = df['price'] + df['tax'] do in pandas?Solution
Step 1: Understand the operation on columns
The expression adds values from 'price' and 'tax' columns for each row.Step 2: Assign result to new column
The sum is stored in a new column named 'total' in the DataFrame.Final Answer:
Creates a new column 'total' by adding 'price' and 'tax' columns element-wise. -> Option DQuick Check:
Adding columns creates new column with sums [OK]
- Thinking it multiplies instead of adds
- Assuming it deletes columns
- Confusing assignment with filtering
df and store the result in a new column 'C'?Solution
Step 1: Identify the subtraction operation
We want to subtract column 'B' from 'A', so the operator is '-'.Step 2: Assign the result to new column 'C'
Usedf['C'] = df['A'] - df['B']to store the difference.Final Answer:
df['C'] = df['A'] - df['B'] -> Option AQuick Check:
Subtraction uses '-' operator between columns [OK]
- Using '+' instead of '-'
- Using '*' or '/' operators incorrectly
- Confusing column names or assignment
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?
Solution
Step 1: Multiply columns 'A' and 'B' element-wise
Row 0: 2 * 3 = 6, Row 1: 4 * 5 = 20.Step 2: Print the new column 'C'
The output shows the values [6, 20] for the two rows.Final Answer:
[6, 20] -> Option AQuick Check:
Element-wise multiplication = [6, 20] [OK]
- Adding instead of multiplying
- Printing wrong column
- Confusing list output format
df['D'] = df['A'] + '5'
Assuming 'A' is a numeric column.
Solution
Step 1: Check data types involved in addition
Column 'A' is numeric, but '5' is a string, so adding them causes a type mismatch.Step 2: Understand pandas behavior on mixed types
Pandas cannot add string to numeric directly, so it raises a TypeError.Final Answer:
It will raise a TypeError because you cannot add a string to a numeric column. -> Option CQuick Check:
Adding string to number causes TypeError [OK]
- Assuming string '5' is converted automatically
- Expecting concatenation with numbers
- Ignoring error messages
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?Solution
Step 1: Subtract discount from cost
Calculate the price after discount:df['cost'] - df['discount'].Step 2: Apply 10% tax on discounted price
Multiply the result by 1.10 to add 10% tax.Step 3: Assign to 'final_price'
Store the final value in the new column 'final_price'.Final Answer:
df['final_price'] = (df['cost'] - df['discount']) * 1.10 -> Option BQuick Check:
Subtract then multiply for tax = correct formula [OK]
- Missing parentheses causing wrong order
- Multiplying discount instead of discounted price
- Applying tax before subtracting discount
Ready to prove it?
Pass the test and this pattern moves unknown
