Introduction to Pandas
Chapter 4: Accessing DataFrame rows and columns
Accessing rows via slicing
Slicing also works for both .loc
and .iloc
. So you can obtain a DataFrame
with a subset of columns.
>>> df.head()
# 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
[5 rows x 12 columns]
You can slice using the index labels.
>>> pokemon_subset = df.loc["Ivysaur":"Charmander"]
>>> print(len(pokemon_subset))
4
>>> print(pokemon_subset)
# Type 1 ... Generation Legendary
Name ...
Ivysaur 2 Grass ... 1 False
Venusaur 3 Grass ... 1 False
VenusaurMega Venusaur 3 Grass ... 1 False
Charmander 4 Fire ... 1 False
[4 rows x 12 columns]
You can also slice using the row number (starting from 0).
>>> pokemon_subset = df.iloc[1:4]
>>> print(len(pokemon_subset))
3
>>> print(pokemon_subset)
# Type 1 ... Generation Legendary
Name ...
Ivysaur 2 Grass ... 1 False
Venusaur 3 Grass ... 1 False
VenusaurMega Venusaur 3 Grass ... 1 False
[3 rows x 12 columns]