0
0
Pandasdata~20 mins

Setting a column as index in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Index Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the output of setting a column as index?
Given the DataFrame:
import pandas as pd
df = pd.DataFrame({"Name": ["Alice", "Bob"], "Age": [25, 30]})
df2 = df.set_index("Name")
print(df2)

What will be printed?
Pandas
import pandas as pd
df = pd.DataFrame({"Name": ["Alice", "Bob"], "Age": [25, 30]})
df2 = df.set_index("Name")
print(df2)
A
   Name  Age
0  Alice   25
1    Bob   30
B
   Age
0   25
1   30
C
Name  Age
Alice 25
Bob 30
D
       Age
Name       
Alice    25
Bob      30
Attempts:
2 left
💡 Hint
Setting a column as index moves that column to the row labels.
📝 Syntax
intermediate
2:00remaining
Which code correctly sets 'ID' as index in pandas?
Choose the code snippet that correctly sets the 'ID' column as the index of DataFrame df.
Pandas
import pandas as pd
df = pd.DataFrame({"ID": [1, 2], "Value": [100, 200]})
Adf.set_index('ID')
Bdf.set_index(ID)
Cdf.set_index(['ID'])
Ddf.set_index(ID, inplace=True)
Attempts:
2 left
💡 Hint
The column name must be a string inside quotes.
optimization
advanced
2:00remaining
How to set a column as index modifying the original DataFrame?
You want to set the 'Date' column as index in DataFrame df and keep the change without creating a new DataFrame. Which option does this efficiently?
Pandas
import pandas as pd
df = pd.DataFrame({"Date": ["2023-01-01", "2023-01-02"], "Sales": [200, 250]})
Adf.index = df.set_index('Date')
Bdf = df.set_index('Date')
Cdf.set_index('Date', inplace=True)
Ddf.index = df['Date']
Attempts:
2 left
💡 Hint
Look for the parameter that changes the DataFrame in place.
🔧 Debug
advanced
2:00remaining
Why does this code raise an error?
Consider this code:
import pandas as pd
df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
df.set_index(A)

Why does it raise an error?
Pandas
import pandas as pd
df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
df.set_index(A)
ATypeError because set_index expects a list
BNameError because A is not defined as a variable
CKeyError because column 'A' does not exist
DSyntaxError due to missing quotes
Attempts:
2 left
💡 Hint
Check if the column name is passed as a string or variable.
🧠 Conceptual
expert
2:00remaining
What happens if you set a column as index but it contains duplicate values?
If you run df.set_index('Category') where 'Category' column has duplicate values, what is the effect on the DataFrame index?
AThe index will allow duplicates, so multiple rows can share the same index label
BThe DataFrame converts the index to a MultiIndex to handle duplicates
CDuplicates are automatically removed from the index
DIt raises a ValueError because index must be unique
Attempts:
2 left
💡 Hint
Think about whether pandas requires index labels to be unique.