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 specific rows and columns

face Josiah Wang

You can also access specific rows and/or columns.

For example, you can access all rows, and a single column.

>>> print(df.loc[:, "Type 1"])
Name
Bulbasaur                  Grass
Ivysaur                    Grass
Venusaur                   Grass
VenusaurMega Venusaur      Grass
Charmander                  Fire
                          ...
Diancie                     Rock
DiancieMega Diancie         Rock
HoopaHoopa Confined      Psychic
HoopaHoopa Unbound       Psychic
Volcanion                   Fire
Name: Type 1, Length: 800, dtype: object

The following example accesses all rows, and multiple columns.

>>> print(df.loc[:, ["Type 1", "Generation"]]) 
Name
Bulbasaur                Grass           1
Ivysaur                  Grass           1
Venusaur                 Grass           1
VenusaurMega Venusaur    Grass           1
Charmander                Fire           1
...                        ...         ...
Diancie                   Rock           6
DiancieMega Diancie       Rock           6
HoopaHoopa Confined    Psychic           6
HoopaHoopa Unbound     Psychic           6
Volcanion                 Fire           6

[800 rows x 2 columns]

Next, we have an example of two rows and two columns.

>>> print(df.loc[["Squirtle", "Pikachu"], ["Type 1", "Generation"]])
            Type 1  Generation
Name
Squirtle     Water           1
Pikachu   Electric           1

You can also access multiple rows and columns by the row/column position.

>>> print(df.iloc[1:3, -4:-2])  # Multiple rows and columns by position
          Sp. Def  Speed
Name
Ivysaur        80     60
Venusaur      100     80