Skip to content
Quantoros

Select the labels 1, 3 and 6 from the second level of the MultiIndexed Series. Assume import pandas as pd and import…

PythonLevel: Intermediatepandas · MultiIndex

Select the labels 1, 3 and 6 from the second level of the MultiIndexed Series.

Assume import pandas as pd and import numpy as np.

Starting data:

letters = ['A', 'B', 'C']
numbers = list(range(10))

mi = pd.MultiIndex.from_product([letters, numbers])
s = pd.Series(np.random.rand(30), index=mi)
Hints
  • First define row granularity, column types and keys.
  • Check index alignment, missing values and output size after the transformation.

Answer

s.loc[:, [1, 3, 6]]

Source and licence: 100 pandas puzzles — Alex Riley and contributors · MIT

Related questions