apply() on columns in Pandas - Time & Space Complexity
We want to understand how the time needed to run apply() on DataFrame columns changes as the data grows.
Specifically, how does the work increase when we apply a function to each column?
Analyze the time complexity of the following code snippet.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(1000, 10))
result = df.apply(lambda col: col.sum(), axis=0)
This code creates a DataFrame with 1000 rows and 10 columns, then sums each column using apply().
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The function runs once per column, processing all rows in that column.
- How many times: It repeats for each of the columns (here, 10 times).
As the number of rows grows, the work to sum each column grows linearly. More rows mean more numbers to add per column.
| Input Size (n rows) | Approx. Operations |
|---|---|
| 10 | 10 columns x 10 rows = 100 operations |
| 100 | 10 columns x 100 rows = 1,000 operations |
| 1000 | 10 columns x 1000 rows = 10,000 operations |
Pattern observation: Operations grow directly with the number of rows. Doubling rows doubles work.
Time Complexity: O(n x m)
This means the time grows proportionally with the number of rows (n) times the number of columns (m).
[X] Wrong: "Applying a function on columns only depends on the number of columns, so it's O(m)."
[OK] Correct: Each column's function processes all rows, so the total work depends on both rows and columns, not just columns.
Understanding how data size affects function application helps you write efficient code and explain your choices clearly in real projects.
What if we changed axis=0 to axis=1 to apply the function on rows instead of columns? How would the time complexity change?
Practice
apply() function do when used on a pandas DataFrame column?Solution
Step 1: Understand the purpose of
Theapply()on columnsapply()method runs a function on each element of the column, transforming or analyzing the data.Step 2: Compare with other options
Deleting, sorting, or merging are not actions performed byapply()on a column.Final Answer:
It applies a function to each value in the column. -> Option AQuick Check:
apply()runs function on each column value [OK]
- Thinking apply() deletes or sorts data
- Confusing apply() with merge or drop functions
- Assuming apply() works on entire DataFrame without axis
df?Solution
Step 1: Identify correct method call syntax
The correct way to use apply on a column isdf['column'].apply(function). df['age'].apply(lambda x: x * 2) matches this.Step 2: Check lambda function usage
df['age'].apply(lambda x: x * 2) correctly passes a lambda function that doubles the value. Other options misuse syntax or assignment.Final Answer:
df['age'].apply(lambda x: x * 2) -> Option CQuick Check:
Use df['col'].apply(lambda x: ...) [OK]
- Using square brackets with apply like a list
- Assigning apply instead of calling it
- Calling apply as a standalone function
df below:score 0 10 1 20 2 30 3 40
What is the output of
df['score'].apply(lambda x: x // 15)?Solution
Step 1: Apply the lambda function to each value
Divide each score by 15 using floor division:
10 // 15 = 0
20 // 15 = 1
30 // 15 = 2
40 // 15 = 2Step 2: Write the resulting Series
The output Series is:
0 0
1 1
2 2
3 2Final Answer:
0 0 1 1 2 2 3 2 Name: score, dtype: int64 -> Option DQuick Check:
Floor division on each value = output [OK]
- Using normal division instead of floor division
- Misreading floor division results
- Confusing output format with DataFrame instead of Series
df['new_col'] = df['value'].apply(x: x + 5)
How can it be fixed?
Solution
Step 1: Identify syntax error in lambda function
The code usesx: x + 5without thelambdakeyword, which is required to define an anonymous function.Step 2: Correct the syntax
Addlambdabefore the function:df['value'].apply(lambda x: x + 5).Final Answer:
Missing lambda keyword; fix: df['value'].apply(lambda x: x + 5) -> Option AQuick Check:
Lambda keyword needed for inline functions [OK]
- Omitting the lambda keyword
- Using incorrect brackets or syntax for lambda
- Thinking apply() can't use inline functions
df with a column 'temperature' in Celsius. You want to create a new column 'temp_f' with Fahrenheit values using apply(). Which code correctly does this?Solution
Step 1: Recall the formula for Celsius to Fahrenheit
The correct formula is Fahrenheit = (Celsius * 9/5) + 32.Step 2: Check each option's lambda function
df['temp_f'] = df['temperature'].apply(lambda c: (c * 9/5) + 32) correctly applies the formula to each value in 'temperature'. df['temp_f'] = df.apply(lambda c: (c * 9/5) + 32) applies to whole DataFrame, C and D have incorrect formulas.Final Answer:
df['temp_f'] = df['temperature'].apply(lambda c: (c * 9/5) + 32) -> Option BQuick Check:
Use correct formula inside apply() on the column [OK]
- Applying function to whole DataFrame instead of column
- Mixing order of operations in formula
- Forgetting parentheses in formula
Ready to prove it?
Pass the test and this pattern moves unknown
