0
0
Pandasdata~20 mins

Selecting columns by name in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Column Selector Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Selecting multiple columns by name
What is the output of this code snippet that selects columns 'A' and 'C' from the DataFrame?
Pandas
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6],
    'C': [7, 8, 9]
})

result = df[['A', 'C']]
print(result)
A
   A  C
0  1  7
1  2  8
2  3  9
B
   A  B  C
0  1  4  7
1  2  5  8
2  3  6  9
C
   B
0  4
1  5
2  6
DKeyError: "['A', 'C'] not in index"
Attempts:
2 left
💡 Hint
Remember to use double brackets to select multiple columns by name.
data_output
intermediate
2:00remaining
Selecting a single column returns a Series
What is the type and output of selecting column 'B' from the DataFrame below?
Pandas
import pandas as pd

df = pd.DataFrame({
    'A': [10, 20],
    'B': [30, 40],
    'C': [50, 60]
})

result = df['B']
print(type(result))
print(result)
A<class 'pandas.core.frame.DataFrame'>\n B\n0 30\n1 40
B<class 'pandas.core.series.Series'>\n0 30\n1 40\nName: B, dtype: int64
C<class 'list'>\n[30, 40]
DKeyError: 'B'
Attempts:
2 left
💡 Hint
Selecting a single column by name returns a Series, not a DataFrame.
🔧 Debug
advanced
2:00remaining
Identify the error when selecting columns
What error does this code raise when trying to select columns 'X' and 'Y' from the DataFrame?
Pandas
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2],
    'B': [3, 4]
})

result = df[['X', 'Y']]
print(result)
ATypeError: unhashable type: 'list'
BAttributeError: 'DataFrame' object has no attribute 'X'
CIndexError: list index out of range
DKeyError: "['X', 'Y'] not in index"
Attempts:
2 left
💡 Hint
Check if the columns exist in the DataFrame before selecting.
🚀 Application
advanced
2:00remaining
Select columns by name using a list variable
Given a list of column names, which option correctly selects those columns from the DataFrame?
Pandas
import pandas as pd

cols = ['A', 'C']
df = pd.DataFrame({
    'A': [5, 6],
    'B': [7, 8],
    'C': [9, 10]
})

result = None  # Fill in the correct selection
Aresult = df[cols]
Bresult = df.cols
Cresult = df[['cols']]
Dresult = df.loc[:, cols]
Attempts:
2 left
💡 Hint
Use the list variable directly inside the brackets to select columns.
🧠 Conceptual
expert
2:00remaining
Difference between selecting columns by single vs double brackets
What is the main difference between df['A'] and df[['A']] when selecting columns in pandas?
ABoth return a Series but with different index labels
Bdf['A'] returns a DataFrame, df[['A']] returns a Series
Cdf['A'] returns a Series, df[['A']] returns a DataFrame
DBoth return a DataFrame but with different column order
Attempts:
2 left
💡 Hint
Think about the data structure type returned by each selection.