First data analysis walkthrough in Data Analysis Python - Time & Space Complexity
When we analyze data, we often run code that looks at many rows. Understanding how the time to run this code grows as the data grows helps us plan better.
We want to know: How does the work change when we have more data?
Analyze the time complexity of the following code snippet.
import pandas as pd
def analyze_data(df):
total = 0
for value in df['numbers']:
total += value
return total
# df is a DataFrame with a column 'numbers'
This code adds up all the numbers in one column of a data table.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the column.
- How many times: Once for every row in the data.
As the number of rows grows, the time to add all numbers grows at the same pace.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: Doubling the data doubles the work.
Time Complexity: O(n)
This means the time to finish grows directly with the number of rows.
[X] Wrong: "Adding numbers in a column takes the same time no matter how big the data is."
[OK] Correct: Each number must be looked at once, so more data means more work.
Knowing how your code grows with data size shows you understand efficiency. This helps you write better data analysis code and explain your thinking clearly.
"What if we used a built-in function like sum() instead of a loop? How would the time complexity change?"
Practice
head() on a DataFrame during the first data analysis walkthrough?Solution
Step 1: Understand the function
Thehead()head()function shows the first few rows of a DataFrame, usually the first 5 rows by default.Step 2: Purpose in data analysis walkthrough
Seeing the first few rows helps you quickly understand what kind of data you have and check if it loaded correctly.Final Answer:
To quickly see the first few rows of the data -> Option CQuick Check:
head()shows first rows [OK]
- Confusing head() with describe()
- Thinking head() gives statistics
- Assuming head() cleans data
df?Solution
Step 1: Identify the function for data types and non-null counts
Theinfo()method on a DataFrame shows data types and counts of non-null values per column.Step 2: Match syntax with DataFrame
Callingdfdf.info()correctly applies this method to the DataFrame nameddf.Final Answer:
df.info() -> Option BQuick Check:
info() shows data types and counts [OK]
- Using describe() to check data types
- Trying summary() which does not exist
- Confusing head() with info()
import pandas as pd
data = {'age': [25, 30, 22, 40, 28], 'salary': [50000, 60000, 45000, 80000, 52000]}
df = pd.DataFrame(data)
summary = df.describe()What will be the output of
summary.loc['mean', 'salary']?Solution
Step 1: Calculate the mean of the 'salary' column
Sum salaries: 50000 + 60000 + 45000 + 80000 + 52000 = 287000. Number of entries: 5. Mean = 287000 / 5 = 57400.0.Step 2: Understand
Thedescribe()outputdescribe()method returns a DataFrame with statistics including 'mean' as an index row. Accessingsummary.loc['mean', 'salary']gives the mean salary value.Final Answer:
57400.0 -> Option DQuick Check:
Mean salary = 57400.0 [OK]
- Adding incorrectly or missing one value
- Confusing mean with median or mode
- Using wrong index or column name
import pandas as pd
data = {'name': ['Alice', 'Bob'], 'age': [25, 30]}
df = pd.DataFrame(data)
print(df.describe())What is the most likely reason for the error or unexpected output?
Solution
Step 1: Check DataFrame columns and types
The DataFrame has a string column 'name' and a numeric column 'age'.Step 2: Understand
By default,describe()behaviordescribe()summarizes only numeric columns. It ignores string columns unless specified.Final Answer:
Thedescribe()method cannot handle string columns by default -> Option AQuick Check:
describe() skips strings by default [OK]
- Expecting describe() to summarize strings automatically
- Thinking DataFrame is empty
- Assuming describe() needs parameters always
df with columns ['product', 'price', 'quantity']. You want to quickly find the average price of products that have quantity greater than 10. Which code snippet correctly performs this first data analysis step?Solution
Step 1: Filter rows where quantity > 10
Usedf[df['quantity'] > 10]to select only rows with quantity greater than 10.Step 2: Calculate mean of 'price' column on filtered data
Access the 'price' column of filtered rows and callmean()to get average price.Final Answer:
df[df['quantity'] > 10]['price'].mean() -> Option AQuick Check:
Filter then mean() gives correct average [OK]
- Passing condition inside mean() incorrectly
- Using mean() on entire DataFrame without filtering
- Wrong syntax for describe()
Ready to prove it?
Pass the test and this pattern moves unknown
