0
0
Pandasdata~20 mins

iloc for position-based selection in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
iloc Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this iloc selection?
Given the DataFrame df below, what is the output of df.iloc[1:3, 0:2]?
Pandas
import pandas as pd

data = {'A': [10, 20, 30, 40], 'B': [5, 15, 25, 35], 'C': [100, 200, 300, 400]}
df = pd.DataFrame(data)

result = df.iloc[1:3, 0:2]
print(result)
A
    A   C
1  20  200
2  30  300
B
    A   B
0  10   5
1  20  15
C
    A   B
1  20  15
2  30  25
D
    B   C
1  15  200
2  25  300
Attempts:
2 left
💡 Hint
Remember iloc uses integer positions for rows and columns, starting at 0, and the end index is exclusive.
data_output
intermediate
1:30remaining
How many rows and columns does this iloc slice return?
Given a DataFrame df with 5 rows and 4 columns, what is the shape of df.iloc[2:5, 1:3]?
Pandas
import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(20).reshape(5,4), columns=list('ABCD'))

result = df.iloc[2:5, 1:3].shape
print(result)
A(3, 2)
B(2, 3)
C(3, 3)
D(2, 2)
Attempts:
2 left
💡 Hint
Count how many rows and columns are included between the start and end indices.
🔧 Debug
advanced
1:30remaining
What error does this iloc code raise?
Consider the code below. What error will it raise when executed?
Pandas
import pandas as pd

data = {'X': [1, 2, 3], 'Y': [4, 5, 6]}
df = pd.DataFrame(data)

result = df.iloc[3, 1]
print(result)
AKeyError: 3
BIndexError: single positional indexer is out-of-bounds
CValueError: cannot index with vector containing NA / NaN values
DTypeError: unhashable type: 'slice'
Attempts:
2 left
💡 Hint
Check the number of rows and the index used in iloc.
🚀 Application
advanced
2:00remaining
Select the correct iloc code to get the last two rows and first column
You have a DataFrame df with 10 rows and 4 columns. Which iloc code correctly selects the last two rows and only the first column?
Adf.iloc[-2:, 0:1]
Bdf.iloc[8:10, 0]
Cdf.iloc[8:10, 0:1]
Ddf.iloc[-2:, 0]
Attempts:
2 left
💡 Hint
Remember that iloc slicing with a single column index returns a Series, but slicing with a range returns a DataFrame.
🧠 Conceptual
expert
2:30remaining
What is the output of this complex iloc selection?
Given the DataFrame df below, what is the output of df.iloc[[0, 2, 4], [1, 3]]?
Pandas
import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame(np.arange(20).reshape(5,4), columns=['W', 'X', 'Y', 'Z'])

result = df.iloc[[0, 2, 4], [1, 3]]
print(result)
A
    X   Z
0   1   3
1   5   7
2   9  11
B
    W   Y
0   0   2
2   8  10
4  16  18
C
    X   Z
1   5   7
3  13  15
4  17  19
D
    X   Z
0   1   3
2   9  11
4  17  19
Attempts:
2 left
💡 Hint
iloc with lists selects specific rows and columns by position, not slices.