This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 4: Accessing DataFrame rows and columns

Accessing rows

face Josiah Wang

Now, let’s try to access rows in a DataFrame. You can access rows in two ways:

  • df.loc: by the index label - like a dict
  • df.iloc: by position (row number) - like a list

Let’s say that our Pokemon DataFrame is indexed by "Name".

>>> df = pd.read_csv("pokemon.csv", index_col="Name")
>>> df.head(10)
                           # Type 1  ... Generation  Legendary
Name                                 ...
Bulbasaur                  1  Grass  ...          1      False
Ivysaur                    2  Grass  ...          1      False
Venusaur                   3  Grass  ...          1      False
VenusaurMega Venusaur      3  Grass  ...          1      False
Charmander                 4   Fire  ...          1      False
Charmeleon                 5   Fire  ...          1      False
Charizard                  6   Fire  ...          1      False
CharizardMega Charizard X  6   Fire  ...          1      False
CharizardMega Charizard Y  6   Fire  ...          1      False
Squirtle                   7  Water  ...          1      False

[10 rows x 12 columns]

To access the row for "Charmeleon" (as a Series object):

>>> charmeleon_series = df.loc["Charmeleon"]
>>> print(type(charmeleon_series))
<class 'pandas.core.series.Series'>
>>> print(charmeleon_series)
#                 5
Type 1         Fire
Type 2          NaN
Total           405
HP               58
Attack           64
Defense          58
Sp. Atk          80
Sp. Def          65
Speed            80
Generation        1
Legendary     False
Name: Charmeleon, dtype: object

You can access the same Series by position (row number), using the .iloc attribute. Charmeleon would be at row 5 (counting from 0).

>>> charmeleon_series = df.iloc[5]
>>> print(charmeleon_series)
### Same as above