5.11. Series Indexing

5.11.1. SetUp

>>> import pandas as pd
>>>
>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>> index = ['a', 'b', 'c', 'd', 'e', 'm']
>>>
>>> s = pd.Series(data, index)
>>>
>>> s
a      Alice
b        Bob
c      Carol
d       Dave
e        Eve
m    Mallory
dtype: str

5.11.2. Equals

  • == operator can be used to compare the series with a value

>>> s == 'Alice'
a     True
b    False
c    False
d    False
e    False
m    False
dtype: bool
>>> s == 'Bob'
a    False
b     True
c    False
d    False
e    False
m    False
dtype: bool

5.11.3. Alternative

  • | operator can be used to combine multiple boolean series

>>> (s == 'Alice') | (s == 'Bob')
a     True
b     True
c    False
d    False
e    False
m    False
dtype: bool

5.11.4. Select

>>> s.loc[s=='Alice']
a    Alice
dtype: str
>>> s.loc[s=='Bob']
b    Bob
dtype: str
>>> s.loc[(s=='Alice') | (s=='Bob')]
a    Alice
b      Bob
dtype: str

5.11.5. Variables

>>> query = (s=='Alice') | (s=='Bob')
>>>
>>> s.loc[query]
a    Alice
b      Bob
dtype: str
>>> alice = (s == 'Alice')
>>> bob = (s == 'Bob')
>>>
>>> s.loc[alice|bob]
a    Alice
b      Bob
dtype: str
>>> alice = (s == 'Alice')
>>> bob = (s == 'Bob')
>>> query = alice | bob
>>>
>>> s.loc[query]
a    Alice
b      Bob
dtype: str

5.11.6. Rationale

>>> s
a      Alice
b        Bob
c      Carol
d       Dave
e        Eve
m    Mallory
dtype: str
>>> query = [True, False, True, False, True, False]
>>>
>>> s.loc[query]
a    Alice
c    Carol
e      Eve
dtype: str

5.11.7. Assignments