02 04 Loops - HannaAA17/Data-Scientist-With-Python-datacamp GitHub Wiki

while loop

# Initialize offset
offset = -6

# Code the while loop
while offset != 0 :
    print("correcting...")
    if offset < 0 :
      offset = offset + 1
    else : 
      offset = offset -1
    print(offset)

for loop

for var in seq:
    expression

indexes and values

# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]

# Change for loop to use enumerate() and update print()
for index,a in enumerate(areas) :
    print("room" + str(index) + ":" + str(a))

loop over list of lists

# house list of lists
house = [["hallway", 11.25], 
         ["kitchen", 18.0], 
         ["living room", 20.0], 
         ["bedroom", 10.75], 
         ["bathroom", 9.50]]
         
# Build a for loop from scratch
for room in house:
    print("the "+room[0]+ " is " + str(room[1]) + " sqm" )

Loop over string

for c in "family":
    print(c.capitalize())

Loop Data Stuctures

Dictionary

for key,val in my_dict.items():

Numpy array

for val in np.nditer(my_array):

Loop over dictionary

# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin',
          'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }
          
# Iterate over europe
for key, value in europe.items():
    print("the capital of " + key + "is "+ value)

Loop over Numpy Array

# Import numpy as np
import numpy as np

# For loop over np_height, 1D array
for x in np_height:
    print(str(x) + " inches")

# For loop over np_baseball, 2D array
for x in np.nditer(np_baseball):
    print(x)

Loop over DataFrame

for lab, row in brics.iterrows() :
    ...
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Iterate over rows of cars
for lab, row in cars.iterrows() :
    print(lab)
    print(row)

<script.py> output:
    US
    cars_per_cap              809
    country         United States
    drives_right             True
    Name: US, dtype: object
    AUS
    cars_per_cap          731
    country         Australia
    drives_right        False
    Name: AUS, dtype: object
    JPN
    cars_per_cap      588
    country         Japan
    drives_right    False
    Name: JPN, dtype: object
    IN
    cars_per_cap       18
    country         India
    drives_right    False
    Name: IN, dtype: object
    RU
    cars_per_cap       200
    country         Russia
    drives_right      True
    Name: RU, dtype: object
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Adapt for loop
for lab, row in cars.iterrows() :
    print(lab + ": " + str(row['cars_per_cap']))

<script.py> output:
    US: 809
    AUS: 731
    JPN: 588
    IN: 18
    RU: 200
    MOR: 70
    EG: 45

Add Columns

Using iterrow() is not efficient since you're creating a new Pandas Serie on each iteration

# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Code for loop that adds COUNTRY column
for lab, row in cars.iterrows() : 
    cars.loc[lab, "COUNTRY"] = row["country"].upper()

# Print cars
print(cars)

apply()

# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Use .apply(str.upper)
cars["COUNTRY"] = cars["country"].apply(str.upper)
⚠️ **GitHub.com Fallback** ⚠️