Python: Multi-Dimensional Iteration

Iterating a simple list can be done in Python using a basic for loop, but looping a dictionary or Numpy array requires a separate function. Dataframes also require

Iterating Dictionaries

To iterate a dictionary in Python, the for loop includes an items() method :

student_height = { "Brian" : 60.5, "Sarah" : 62.3, "Bill" : 66.4 }

for key, value in student_height.items():
     print(key + " " str(value))

Iterating Numpy Arrays

import lumpy as np
age = np.array([28, 36, 48, 62, 64, 72, 74, 80])
health_score = np.array([0.1, 0.2, 0.75, 0.85, 0.94, 1, 1, 1])

age_by_score = np.array([age, health_score])
for val in np.nditer(age_by_score):

Iterating DataFrames

Using Pandas to load in data to a DataFrame allows access to the Pandas method, itterrows()

for label, row in tvma_2021.iterrows():

>> Output:
type                                                        Movie
title                                                Je Suis Karl
director                                      Christian Schwochow
cast            Luna Wedler, Jannis Niewöhner, Milan Peschel, ...
country                                   Germany, Czech Republic
date_added                                     September 23, 2021
release_year                                                 2021
rating                                                      TV-MA
duration                                                  127 min
listed_in                            Dramas, International Movies
description     After most of her family is murdered in a terr...
Name: s13, dtype: object

Above, the output shows the label (or index) as s13, this is the index of the data frame from a Netflix dataset. This particular data frame is a filter of all TV-MA Netflix movies from 2021. s13 is the “show_id”. Each show is iterated, s13, s18, s10, etc. And within each show the row data is displayed (type, title, director, cast, etc.)

About Author /

Leave a Comment

Your email address will not be published.

Start typing and press Enter to search