A For Loop is a method of iterating through a string, list, dictionary, data frame, series, or anything else that you would like to iterate through. To iterate means to go through an item that makes up a variable. What the item type is depends on what you are iterating through.
The structure of a For Loop looks like this:
To iterate through a:
- String, is to go letter by letter
- List, is to go entry by entry
- Dictionary, is go through key by key, value by value, or key value by key value. If unfamiliar with dictionaries, we have a section for that!
- The key is the item before the colon, “:”, and the value is the item after the the colon. It looks like this “key : value”.
- Data frame, is to go through row by row or column by column. If unfamiliar with data frames, we have a section for that too!
- First, we need a data frame to work with!
Let’s see what the data frame looks like.
By default, iterating through a data frame will iterate over the columns
In order to iterate over the rows, we have to call the .iterrows() method. In addition, we need to identify which series (a.k.a. a column) we want to get the values from. If we don’t identify which series we are interested in, Python will output each observation will all the column values associated with that observation.
- Series, is to go through observation by observation. If unfamiliar with series, we have a section for that!
- Iterating through a series is identical to iterating through the rows of a data frame with the column identified- the Python code just looks different
For Loop within a For Loop
You can have a For Loop within a For Loop. By implementing this technique, Python will iterate through the item(s) that make up that item. This will be demonstrated by using our lst example with the item in the first index (first row or first observation).