Skip to content
Quantoros

Given the lists letters = ['A', 'B', 'C'] and numbers = list(range(10)), construct a MultiIndex object from the…

PythonLevel: Intermediatepandas · MultiIndex

Given the lists letters = ['A', 'B', 'C'] and numbers = list(range(10)), construct a MultiIndex object from the product of the two lists. Use it to index a Series of random numbers. Call this Series s.

Assume import pandas as pd and import numpy as np.

Hints
  • First define row granularity, column types and keys.
  • Check index alignment, missing values and output size after the transformation.

Answer

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

mi = pd.MultiIndex.from_product([letters, numbers])
s = pd.Series(np.random.rand(30), index=mi)
s

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

Related questions