Selecting multiple columns in Pandas - Time & Space Complexity
We want to understand how the time it takes to select multiple columns from a table grows as the table gets bigger.
Specifically, how does the work change when the number of rows or columns changes?
Analyze the time complexity of the following code snippet.
import pandas as pd
n = 10 # Example value for n
data = pd.DataFrame({
'A': range(n),
'B': range(n),
'C': range(n),
'D': range(n)
})
selected = data[['A', 'C']]
This code creates a table with n rows and 4 columns, then selects two columns from it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Copying data from the selected columns for all rows.
- How many times: Once for each row in the table (n times).
As the number of rows grows, the work to select columns grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations (copying 2 columns for 10 rows) |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to select columns grows in a straight line as the number of rows increases.
[X] Wrong: "Selecting columns is instant and does not depend on the number of rows."
[OK] Correct: Even though we only pick columns, pandas must copy data for every row, so more rows mean more work.
Understanding how data selection scales helps you write efficient code and explain your choices clearly in real projects.
"What if we selected all columns instead of just two? How would the time complexity change?"
Practice
'A' and 'B' from a pandas DataFrame df?Solution
Step 1: Understand pandas column selection syntax
To select multiple columns, pandas requires a list of column names inside double brackets.Step 2: Apply correct syntax for multiple columns
Usingdf[['A', 'B']]correctly selects columns 'A' and 'B'. Other options are invalid syntax or select rows instead.Final Answer:
df[['A', 'B']] -> Option CQuick Check:
Multiple columns = list inside double brackets [OK]
- Using single brackets with comma-separated names
- Using bitwise operators like & between column names
- Using .loc incorrectly for column selection
'X' and 'Y' from DataFrame df?Solution
Step 1: Recall syntax for selecting multiple columns
Using double brackets with a list of column names is the standard way:df[['X', 'Y']].Step 2: Check other options for correctness
df.loc[:, 'X', 'Y']causes TypeError (invalid arguments to loc);df['X', 'Y']raises KeyError (tuple not a column);df.loc['X', 'Y']is incorrect syntax.Final Answer:
df[['X', 'Y']] -> Option DQuick Check:
Double brackets with list = correct syntax [OK]
- Using single brackets with multiple column names
- Confusing .loc row and column selection syntax
- Using tuple instead of list inside brackets
df below:A B C 0 1 4 7 1 2 5 8 2 3 6 9
What is the output of
df[['B', 'C']]?Solution
Step 1: Identify columns requested
The code selects columns 'B' and 'C' from the DataFrame.Step 2: Extract columns 'B' and 'C' values
Columns 'B' and 'C' have values [[4,7],[5,8],[6,9]] for rows 0,1,2 respectively.Final Answer:
B C 0 4 7 1 5 8 2 6 9 -> Option AQuick Check:
Selected columns 'B' and 'C' output matchesB C 0 4 7 1 5 8 2 6 9
[OK]
- Confusing columns selected and expecting all columns
- Getting KeyError by misspelling column names
- Selecting rows instead of columns
df = pd.DataFrame({'X':[1,2], 'Y':[3,4]})
selected = df['X', 'Y']Solution
Step 1: Analyze the indexing syntax
The code uses single brackets with a comma, creating a tuple key ('X', 'Y').Step 2: Understand pandas error type
This raises KeyError because pandas looks for a column named ('X', 'Y'), which doesn't exist.Final Answer:
KeyError -> Option BQuick Check:
Tuple key in single brackets causes KeyError [OK]
- Using comma inside single brackets for multiple columns
- Expecting no error with wrong syntax
- Confusing TypeError with KeyError
df with columns ['Name', 'Age', 'City', 'Salary']. You want to create a new DataFrame df_selected with only 'Name' and 'Salary'. Which code correctly does this and also resets the index?Solution
Step 1: Select columns 'Name' and 'Salary'
Use double brackets with list:df[['Name', 'Salary']]to select these columns.Step 2: Reset index without adding old index as column
Usereset_index(drop=True)to reset index and drop old index column.Step 3: Check other options
df.loc[:, ['Name', 'Salary']].reset_index()resets index but keeps old index as column. Usingreset_index()withoutdrop=True(default behavior) keeps the old index as a new column.Final Answer:
df_selected = df[['Name', 'Salary']].reset_index(drop=True) -> Option AQuick Check:
Select columns + reset index drop old index = df_selected = df[['Name', 'Salary']].reset_index(drop=True) [OK]
- Forgetting to use double brackets for multiple columns
- Not using drop=True in reset_index to avoid old index column
- Using .loc without understanding index reset effect
Ready to prove it?
Pass the test and this pattern moves unknown
