6.9. DataFrame Getitem

  • DataFrame[column] - select a column

  • DataFrame[[column1, column2, ...]] - select multiple columns

  • DataFrame[start:stop] - slice rows

  • DataFrame[start:stop:step] - slice rows

6.9.1. SetUp

>>> import pandas as pd
>>>
>>> df = pd.DataFrame([
...     {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
...     {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
...     {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
... ], index=['a', 'b', 'c'])
>>> df
  firstname    lastname  age
a     Alice     Apricot   30
b       Bob  Blackthorn   31
c     Carol        Corn   32

6.9.2. Columns

  • DataFrame[column] - select a column

  • DataFrame[[column1, column2, ...]] - select multiple columns

>>> df['firstname']
a    Alice
b      Bob
c    Carol
Name: firstname, dtype: str
>>> df[['firstname', 'lastname']]
  firstname    lastname
a     Alice     Apricot
b       Bob  Blackthorn
c     Carol        Corn

6.9.3. Rows

  • DataFrame[start:stop] - slice rows

  • DataFrame[start:stop:step] - slice rows

>>> df[0:2]
  firstname    lastname  age
a     Alice     Apricot   30
b       Bob  Blackthorn   31
>>> df[::2]
  firstname lastname  age
a     Alice  Apricot   30
c     Carol     Corn   32

6.9.4. Errors

>>> df['a']
Traceback (most recent call last):
KeyError: 'a'
>>> df[0]
Traceback (most recent call last):
KeyError: 0
>>> df[[0,1]]
Traceback (most recent call last):
KeyError: "None of [Index([0, 1], dtype='int64')] are in the [columns]"

6.9.5. Assignments