Chapter 4: Accessing DataFrame rows and columns

Iterating over columns and rows

face Josiah Wang

Iterating over columns

Iterating over a DataFrame object gives you the column names

>>> for col in df:
...     print(col)
...
#
Type 1
Type 2
Total
HP
Attack
Defense
Sp. Atk
Sp. Def
Speed
Generation
Legendary

To iterate over both (column names, Series) pairs, use .items(). Try the following and observe the output.

for (col, series) in df.items:
    print(f"COLUMN: {col}\n")
    print(f"SERIES:\n{series}\n") 

Iterating over rows

To iterate over rows, you can use either .iterrows() or .itertuples().

Try to figure out what the difference between these two choices are! What does each of them actually return? (They are both different!)

for (row_index, row) in df.iterrows():
    print(row_index, "\n")
    print(row, "\n")

for row in df.itertuples():
    print(row)