IMPLICIT CREATION OF MULTI-INDEXED OBJECTS
In the previous couple articles in the Pandas series we were talking about multi-indexed objects. But sometimes multi-indexed objects are created behind the scenes. The two common scenarios involve passing the following to the constructor of a Series or DataFrame object:
- multiple index arrays
- dictionaries where the keys are tuples containing the indices
Let’s have a look at them now.
MULTIPLE INDEX ARRAYS
Passing multiple (often two, but there may be more) index array is a quick way of creating a multi-indexed object. Hare’s an example:
In [2]:
import numpy as np
import pandas as pd
# Let's create a DataFrame with random numeric data.
# The arguments passed to the np.random.randint functions are:
# 1000 - from value, inclusive
# 2000 - to value, exclusive
# (4, 4) - shape
a = pd.DataFrame(np.random.randint(1000, 2000, (4, 4)),
index=[['shirts', 'shirts', 'pants', 'pants'], ['blue', 'red', 'blue', 'red']],
columns=['spring', 'summer', 'fall', 'winter'])
# And here's our multi-indexed DataFrame object.
a
Out[2]:
DICTIONARIES
The other method of implicitly creating multi-indexed objects is by means of dictionaries. We just have to pass the indices in tuples as keys. Here’s an example:
In [3]:
# This time we'll create a Series object.
# Let's define the dictionary with our data.
data = {('product 1', 'regular price'): 125,
('product 1', 'reduced price'): 84,
('product 2', 'regular price'): 265,
('product 2', 'reduced price'): 182,
('product 3', 'regular price'): 350,
('product 3', 'reduced price'): 280}
# Let's use the dictionary in the constructor of a Series object.
b = pd.Series(data)
# Here's our multi-indexed object.
b
Out[3]:
In the next article we’ll see how to explicitly create multi-indexed objects.