Bird
Raised Fist0
Pandasdata~20 mins

xs() for cross-section selection in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Cross-Section Selector Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of xs() on MultiIndex DataFrame
What is the output of the following code snippet using xs() to select a cross-section from a MultiIndex DataFrame?
Pandas
import pandas as pd

index = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 1), ('B', 2)], names=['letter', 'number'])
data = {'value': [10, 20, 30, 40]}
df = pd.DataFrame(data, index=index)

result = df.xs('A', level='letter')
print(result)
A
letter  value
A       10
A       20
B
   value
letter       
A        10
A        20
C
value
0     10
1     20
D
   value
number       
1        10
2        20
Attempts:
2 left
💡 Hint
Remember that xs() selects data at a particular level of a MultiIndex.
❓ data_output
intermediate
1:30remaining
Number of rows after xs() selection
Given the DataFrame below, how many rows does the result have after applying df.xs(2, level='number')?
Pandas
import pandas as pd

index = pd.MultiIndex.from_tuples([('X', 1), ('X', 2), ('Y', 1), ('Y', 2), ('Z', 2)], names=['letter', 'number'])
data = {'score': [5, 10, 15, 20, 25]}
df = pd.DataFrame(data, index=index)

result = df.xs(2, level='number')
A3
B2
C5
D1
Attempts:
2 left
💡 Hint
Count how many rows have the index level 'number' equal to 2.
🔧 Debug
advanced
1:30remaining
Identify the error in xs() usage
What error does the following code raise when using xs() incorrectly?
Pandas
import pandas as pd

index = pd.MultiIndex.from_tuples([('a', 1), ('b', 2)], names=['letter', 'number'])
data = {'val': [100, 200]}
df = pd.DataFrame(data, index=index)

result = df.xs('c', level='letter')
AKeyError
BTypeError
CValueError
DAttributeError
Attempts:
2 left
💡 Hint
Check what happens when the key is not found in the specified index level.
🚀 Application
advanced
2:00remaining
Using xs() to select columns in a MultiIndex DataFrame
Given a DataFrame with MultiIndex columns, which xs() call correctly selects the cross-section for the column level 'metric' with value 'height'?
Pandas
import pandas as pd

arrays = [['height', 'height', 'weight', 'weight'], ['min', 'max', 'min', 'max']]
columns = pd.MultiIndex.from_arrays(arrays, names=['metric', 'stat'])
 data = [[150, 180, 60, 80], [160, 190, 65, 85]]
df = pd.DataFrame(data, columns=columns)

# Which xs() call selects the 'height' metric columns?
Adf.xs('height', level='stat', axis=0)
Bdf.xs('height', level='metric', axis=1)
Cdf.xs('height', level='metric', axis=0)
Ddf.xs('height', level='stat', axis=1)
Attempts:
2 left
💡 Hint
Remember that columns are selected with axis=1 and the level name must match the MultiIndex level.
🧠 Conceptual
expert
1:30remaining
Effect of drop_level parameter in xs()
What is the effect of setting drop_level=False in the xs() method when selecting a cross-section from a MultiIndex DataFrame?
AThe DataFrame is converted to a Series.
BThe selected level is removed from the index after selection.
CThe selected level remains in the index after selection.
DThe selection returns all levels except the specified one.
Attempts:
2 left
💡 Hint
Think about whether the index level you select stays or is dropped.

Practice

(1/5)
1. What does the xs() method do in pandas?
easy
A. Removes duplicate rows from the DataFrame.
B. Sorts the DataFrame by index values.
C. Selects data by label from rows or columns, especially in multi-index DataFrames.
D. Converts DataFrame to a NumPy array.

Solution

  1. Step 1: Understand the purpose of xs()

    xs() is used to select data by label from rows or columns, especially useful for multi-index DataFrames.
  2. Step 2: Compare with other options

    Sorting, removing duplicates, or converting to arrays are different methods and not related to xs().
  3. Final Answer:

    Selects data by label from rows or columns, especially in multi-index DataFrames. -> Option C
  4. Quick Check:

    xs() = select by label [OK]
Hint: Remember: xs() picks data by label from multi-index [OK]
Common Mistakes:
  • Confusing xs() with sorting methods
  • Thinking xs() removes duplicates
  • Assuming xs() converts data formats
2. Which of the following is the correct syntax to select the cross-section labeled 'B' from the first level of a multi-index DataFrame df using xs()?
easy
A. df.xs('B', level=0)
B. df.xs(level=0, 'B')
C. df.xs('B', axis=1)
D. df.xs('B', level=1)

Solution

  1. Step 1: Recall xs() syntax

    The correct syntax is df.xs(key, level=level_number) where key is the label and level is the index level.
  2. Step 2: Match the label and level

    To select label 'B' from level 0, use df.xs('B', level=0). Other options have wrong argument order or wrong level.
  3. Final Answer:

    df.xs('B', level=0) -> Option A
  4. Quick Check:

    xs(key, level=0) = correct syntax [OK]
Hint: Use xs('label', level=level_number) for multi-index [OK]
Common Mistakes:
  • Swapping arguments order in xs()
  • Using wrong level number
  • Confusing axis parameter with level
3. Given the following DataFrame df with a multi-index:
import pandas as pd
index = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 1), ('B', 2)])
data = {'Value': [10, 20, 30, 40]}
df = pd.DataFrame(data, index=index)
print(df.xs('B', level=0))

What is the output?
medium
A. Value 1 30 2 40
B. Value 0 30 1 40
C. Value 70 Name: B, dtype: int64
D. KeyError: 'B'

Solution

  1. Step 1: Understand the DataFrame structure

    The DataFrame has a multi-index with levels: first level 'A' or 'B', second level 1 or 2, and values 10, 20, 30, 40.
  2. Step 2: Apply xs('B', level=0)

    This selects all rows where the first index level is 'B', returning rows with second level 1 and 2 and their values.
  3. Final Answer:

    Value 1 30 2 40 -> Option A
  4. Quick Check:

    xs('B', level=0) returns rows with first index 'B' [OK]
Hint: xs() filters rows by label at specified level [OK]
Common Mistakes:
  • Expecting sum instead of filtered rows
  • Confusing index levels
  • Mistaking output format
4. Consider this code snippet:
import pandas as pd
index = pd.MultiIndex.from_tuples([('X', 'a'), ('X', 'b'), ('Y', 'a')])
data = {'Score': [5, 10, 15]}
df = pd.DataFrame(data, index=index)
result = df.xs('a')
print(result)

What is the issue with this code?
medium
A. It works fine and prints the rows with second level 'a'.
B. It returns all rows because xs() without level selects all.
C. It returns only the first row incorrectly.
D. It raises a KeyError because level is not specified in xs().

Solution

  1. Step 1: Check the multi-index levels

    The DataFrame has two index levels: first level 'X' or 'Y', second level 'a' or 'b'.
  2. Step 2: Understand xs() without level

    Calling xs('a') without specifying level causes pandas to look for 'a' in the outermost level, which does not exist, raising a KeyError.
  3. Final Answer:

    It raises a KeyError because level is not specified in xs(). -> Option D
  4. Quick Check:

    xs() needs level for multi-index [OK]
Hint: Always specify level in xs() for multi-index to avoid errors [OK]
Common Mistakes:
  • Assuming xs() guesses the level automatically
  • Expecting xs() to return partial matches
  • Ignoring the need for level parameter
5. You have a DataFrame df with a three-level index: ['Country', 'Year', 'City']. You want to select all data for the year 2020 regardless of country or city. Which xs() call will achieve this?
hard
A. df.xs('Year', level=2020)
B. df.xs(2020, level='Year')
C. df.xs(2020, level='City')
D. df.xs('2020', level='Year')

Solution

  1. Step 1: Identify the index level for selection

    The index levels are 'Country', 'Year', and 'City'. We want to select by the 'Year' level with value 2020.
  2. Step 2: Use xs() with correct key and level

    Use df.xs(2020, level='Year') to select all rows where 'Year' is 2020. Other options have wrong argument order, wrong level, or wrong data type.
  3. Final Answer:

    df.xs(2020, level='Year') -> Option B
  4. Quick Check:

    xs(value, level='Year') selects year 2020 [OK]
Hint: Use xs(value, level='LevelName') to select multi-index slices [OK]
Common Mistakes:
  • Swapping level and key arguments
  • Using string '2020' instead of integer 2020
  • Selecting wrong index level
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard