Selecting columns in Data Analysis Python - Time & Space Complexity
When we select columns from a dataset, we want to know how the time to do this changes as the dataset grows.
We ask: How does the work increase when the number of rows or columns grows?
Analyze the time complexity of the following code snippet.
import pandas as pd
def select_columns(df, cols):
return df[cols]
# Example usage:
# df is a DataFrame with many rows and columns
# cols is a list of column names to select
This code returns a new DataFrame with only the columns listed in cols.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Processing each selected column.
- How many times: Once for each column in
cols.
As the number of selected columns grows, the work grows linearly because each selected column must be incorporated into the new DataFrame.
| Input Size (columns) | Approx. Operations |
|---|---|
| 10 | 10 times the work per column |
| 100 | 100 times the work per column |
| 1000 | 1000 times the work per column |
Pattern observation: The work grows directly with the number of columns.
Time Complexity: O(m)
This means the time to select columns grows in a straight line as the number of columns increases.
[X] Wrong: "Selecting columns is instant and does not depend on the number of columns."
[OK] Correct: Even though we only pick columns, the system still processes each selected column to build the new DataFrame, so time grows with columns.
Understanding how data selection scales helps you explain your code choices clearly and shows you know what happens behind the scenes.
"What if we select only one column instead of many? How would the time complexity change?"
Practice
'Age' from a DataFrame df?Solution
Step 1: Understand single column selection syntax
To select one column from a DataFrame, usedf['column_name'].Step 2: Check each option
df['Age']usesdf['Age'], which is correct.df[['Age']]returns a DataFrame, not a Series.df.Age()uses parentheses incorrectly.df.select('Age')is not a valid pandas method.Final Answer:
df['Age'] -> Option DQuick Check:
Single column selection = df['Age'] [OK]
- Using double brackets for single column returns DataFrame, not Series
- Using dot notation with parentheses like a function
- Trying non-existent methods like select()
'Name' and 'Salary' from DataFrame df?Solution
Step 1: Recall syntax for selecting multiple columns
Use double brackets with a list of column names:df[['col1', 'col2']].Step 2: Evaluate options
df[['Name', 'Salary']]matches the correct syntax.df['Name', 'Salary']is invalid syntax.df.Name, df.Salaryselects columns separately, not together.df.select(['Name', 'Salary'])is not a pandas method.Final Answer:
df[['Name', 'Salary']] -> Option BQuick Check:
Multiple columns = df[['Name', 'Salary']] [OK]
- Using single brackets with multiple column names separated by commas
- Trying to select multiple columns with dot notation
- Using non-existent select() method
df below:Name Age Salary 0 John 28 50000 1 Anna 22 60000 2 Mike 32 55000
What is the output of
df[['Name', 'Age']]?Solution
Step 1: Understand what
This selects only the columns 'Name' and 'Age' from the DataFrame, returning a smaller DataFrame with those columns.df[['Name', 'Age']]doesStep 2: Match output to options
Name Age 0 John 28 1 Anna 22 2 Mike 32
shows only 'Name' and 'Age' columns with all rows, which matches the expected output.Name Age Salary 0 John 28 50000 1 Anna 22 60000 2 Mike 32 55000
includes 'Salary' which is not selected.0 John 1 Anna 2 Mike Name: Name, dtype: object
shows only the 'Name' column as a Series.28 22 32
shows only ages as a list, which is incorrect.Final Answer:
DataFrame with columns 'Name' and 'Age' only -> Option AQuick Check:
Selected columns = 'Name' and 'Age' only [OK]
- Expecting single brackets to return multiple columns
- Confusing Series output with DataFrame output
- Including unselected columns in output
'Score' from DataFrame df?
df.Score()
Solution
Step 1: Understand dot notation for column selection
Dot notation selects columns as attributes without parentheses, likedf.Score.Step 2: Identify error in code
Using parentheses()afterScoretries to call it like a function, causing an error.Final Answer:
Parentheses cause an error; dot notation should be without () -> Option AQuick Check:
Dot notation = df.Score without parentheses [OK]
- Adding parentheses after column name with dot notation
- Thinking dot notation works for all column names
- Using double brackets with dot notation
df with columns 'A', 'B', 'C', and 'D'. You want to create a new DataFrame df_new that contains only columns 'B' and 'D' but in reverse order ('D' first, then 'B'). Which code correctly does this?Solution
Step 1: Understand column selection order
The order of columns in the list inside double brackets determines the order in the new DataFrame.Step 2: Check each option
df_new = df[['D', 'B']]selects columns 'D' then 'B', which matches the requirement.df_new = df[['B', 'D']]selects 'B' then 'D', wrong order.df_new = df['D', 'B']is invalid tuple syntax inside single brackets.df_new = df[['B', 'D']].reindex(columns=['B', 'D'])reindexes to the same order 'B' then 'D', incorrect.Final Answer:
df_new = df[['D', 'B']] -> Option CQuick Check:
Order columns by list inside double brackets [OK]
- Selecting columns in wrong order
- Using reindex but specifying the original order
- Using tuple inside single brackets for multiple columns
Ready to prove it?
Pass the test and this pattern moves unknown
