xs() to select a cross-section from a MultiIndex DataFrame?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)
xs() selects data at a particular level of a MultiIndex.The xs() method selects rows at the specified level value. Here, selecting 'A' at level 'letter' returns rows where the first index level is 'A'. The resulting DataFrame has the remaining index level 'number' as its index.
df.xs(2, level='number')?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')
The xs() method selects all rows where the 'number' level equals 2. The tuples with 'number' 2 are ('X', 2), ('Y', 2), and ('Z', 2), so there are 3 rows.
xs() incorrectly?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')
Using xs() with a key that does not exist in the specified level raises a KeyError because the key is missing from the MultiIndex.
xs() call correctly selects the cross-section for the column level 'metric' with value 'height'?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?
The DataFrame has MultiIndex columns with levels 'metric' and 'stat'. To select columns where 'metric' is 'height', use xs('height', level='metric', axis=1).
drop_level=False in the xs() method when selecting a cross-section from a MultiIndex DataFrame?By default, xs() drops the level used for selection from the resulting index. Setting drop_level=False keeps that level in the index.