Kelley Brady
Kelley Brady

Reputation: 390

Select entries in pandas series based on one part of multi-index

I have a Pandas series constructed like this

import itertools
import pandas as pd

combos = list(itertools.permutations(['BB', 'BW', 'WW'], 2))

combo_values = pd.Series([2,4,0,2,0,0], combos)

So combo_values looks like this

(BB, BW)    2
(BB, WW)    4
(BW, BB)    0
(BW, WW)    2
(WW, BB)    0
(WW, BW)    0
dtype: int64

I know you can extract one entry like this

combo_values['BB', 'BW']

So I was thinking to extract the first two entries I would like to do something like this:

combo_values['BB',]

#or this

combo_values['BB',:]

Neither works, and the first option generates the following errors (I am chopping out the traces)

TypeError: 'tuple' object cannot be interpreted as an integer

KeyError: ('BB',)

I know that this alternative solution works:

combo_df = pd.DataFrame(combos, columns = ['A', 'B'])
combo_df['combo_values'] = [2,4,0,2,0,0]
combo_df.loc[combo_df['A'] == 'BB', :]

But is there a way to do this with my combo_values series?

Thank you

Upvotes: 3

Views: 97

Answers (1)

Kelley Brady
Kelley Brady

Reputation: 390

The correct way to do this is to use a multi-index, rather than a tuple-index:

import itertools
import pandas as pd

combos = list(itertools.permutations(['BB', 'BW', 'WW'], 2))

multi = pd.MultiIndex.from_tuples(combos)

combo_values = pd.Series([2,4,0,2,0,0], multi)

combo_values now looks like this:

BB  BW    0.25
    WW    0.50
BW  BB    0.00
    WW    0.25
WW  BB    0.00
    BW    0.00
dtype: float64

And it can be filtered like this:

combo_values['BB',]

To yield

BW    0.25
WW    0.50

Upvotes: 2

Related Questions