Memory-efficient operations in Data Analysis Python - Time & Space Complexity
When working with large data, how fast our code runs matters a lot. Here, we look at how memory-efficient operations affect the time it takes to process data.
We want to know how the speed changes as data size grows when using memory-friendly methods.
Analyze the time complexity of the following code snippet.
import pandas as pd
def process_data():
for chunk in pd.read_csv('large_file.csv', chunksize=1000):
filtered = chunk[chunk['value'] > 10]
# process filtered chunk
print(filtered.shape[0])
# Process data in chunks
process_data()
This code reads a large CSV file in small parts, filters each part, and processes it to save memory.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over chunks of data read from the file.
- How many times: Number of chunks, which depends on total rows divided by chunk size.
As the total data size grows, the number of chunks grows proportionally.
| Input Size (rows) | Approx. Number of Chunks |
|---|---|
| 10,000 | 10 |
| 100,000 | 100 |
| 1,000,000 | 1000 |
Pattern observation: The number of operations grows linearly with the input size because each row is processed once in some chunk.
Time Complexity: O(n)
This means the time to process data grows directly in proportion to the number of rows.
[X] Wrong: "Reading data in chunks makes the process faster than reading all at once."
[OK] Correct: Chunking saves memory but does not reduce total processing time; it still reads and processes all rows once.
Understanding how memory-efficient methods affect time helps you explain practical trade-offs clearly. This skill shows you can handle big data thoughtfully.
"What if we increased the chunk size to process more rows at once? How would the time complexity change?"
Practice
Solution
Step 1: Understand memory usage of data types
Text columns with repeated values use more memory as strings than as categories.Step 2: Apply category conversion
Converting text columns to 'category' type stores unique values once, saving memory.Final Answer:
Convert text columns to 'category' data type -> Option CQuick Check:
Category type reduces memory for repeated text [OK]
- Thinking increasing integer size saves memory
- Loading full dataset without chunking
- Using print for memory optimization
Solution
Step 1: Recall pandas chunk reading parameter
The correct parameter to read in chunks is 'chunksize'.Step 2: Match syntax
Only pd.read_csv('file.csv', chunksize=1000) uses 'chunksize=1000', which is correct syntax.Final Answer:
pd.read_csv('file.csv', chunksize=1000) -> Option AQuick Check:
chunksize=1000 reads file in 1000-row chunks [OK]
- Using 'chunk' instead of 'chunksize'
- Using 'size' or 'batch' which are invalid
- Forgetting to specify chunk size
import pandas as pd
import numpy as np
df = pd.DataFrame({
'A': np.random.randint(0, 100, 5),
'B': ['cat', 'dog', 'cat', 'dog', 'cat']
})
df['B'] = df['B'].astype('category')
print(df.memory_usage(deep=True))Solution
Step 1: Understand astype('category') effect
Converting column 'B' to category reduces memory by storing unique values once.Step 2: Interpret memory_usage(deep=True)
This method shows memory used by each column including actual string data size.Final Answer:
Shows memory usage with 'B' column using less memory than object type -> Option DQuick Check:
Category type reduces memory usage [OK]
- Expecting error from astype conversion
- Thinking category uses more memory
- Confusing print output with DataFrame display
import pandas as pd
df = pd.read_csv('data.csv')
df['col'] = df['col'].astype('category')
df = df.astype({'num_col': 'int8'})
print(df.memory_usage())Solution
Step 1: Check int8 range suitability
int8 supports values from -128 to 127; larger values cause overflow.Step 2: Identify potential overflow risk
If 'num_col' has values outside int8 range, conversion causes incorrect data.Final Answer:
Using 'int8' may cause overflow if values exceed range -> Option AQuick Check:
int8 range limits can cause data errors [OK]
- Assuming all int conversions are safe
- Believing memory_usage() ignores changes
- Thinking astype fails after CSV read
Solution
Step 1: Use category for repeated strings
Converting 'status' to category stores unique values once, saving memory.Step 2: Downcast numeric columns
Downcasting numeric columns to smallest integer type reduces memory without losing data.Step 3: Evaluate other options
Keeping strings as object or dropping columns wastes memory or data; object type uses more memory.Final Answer:
Convert 'status' to category type and downcast numeric columns to smallest possible integer type. -> Option BQuick Check:
Category + downcast = best memory saving [OK]
- Dropping useful columns unnecessarily
- Keeping strings as object wastes memory
- Converting all to object increases memory
Ready to prove it?
Pass the test and this pattern moves unknown
