Skip to content
Home » pandas Part 15 – Implicit Creation of Multi-Indexed Objects

pandas Part 15 – Implicit Creation of Multi-Indexed Objects

Spread the love

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]:
spring summer fall winter
shirts blue 1180 1438 1838 1507
red 1335 1604 1998 1845
pants blue 1628 1329 1951 1174
red 1345 1560 1587 1535

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]:
product 1  regular price    125
           reduced price     84
product 2  regular price    265
           reduced price    182
product 3  regular price    350
           reduced price    280
dtype: int64

In the next article we’ll see how to explicitly create multi-indexed objects.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply