Now if we want to repeat things we can use a wide variety of tools. Like :
While loops
Repeating action until condition is met
while condition : expression error = 50.0 while error > 1 : error = error / 4 print(error)
Do not forget to increment the condition to avoid being stuck in an infinite loop. If your are just ctrl+c to stop the calculation
For loops
For each var in seq, execute expression. If you want to also get the index you have to use the enumerate method and add index in the var expression :
for var in seq : expression fam = [1.73, 1.68, 1.71, 1.89] for height in fam : print(height) for index, height in enumerate(fam) : print("index " + str(index) + ": " + str(height))
You can also loop on strings and then get all the letters from the word :
for c in "family" : print(c.capitalize()) -> F A M I L Y
You can also loops on lists 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 i in house: print('the '+i[0]+' is '+str(i[1])+' sqm')
Loop Data Structures : Dictionary
world = { "afghanistan":30.55, "albania":2.77, "algeria":39.21 } for key, value in world.items() : print(key + " -- " + str(value))
You have to unpack the dictionary using .items() and then loop on key and value.
Numpy Arrays
import numpy as np np_height = np.array([1.73, 1.68, 1.71, 1.89, 1.79]) np_weight = np.array([65.4, 59.2, 63.6, 88.4, 68.7]) bmi = np_weight / np_height ** 2 for val in bmi : print(val) -> 21.852 20.975 21.750 24.747 21.441
2D Numpy Arrays
import numpy as np np_height = np.array([1.73, 1.68, 1.71, 1.89, 1.79]) np_weight = np.array([65.4, 59.2, 63.6, 88.4, 68.7]) meas = np.array([np_height, np_weight]) for val in meas : print(val) -> [ 1.73 1.68 1.71 1.89 1.79] [ 65.4 59.2 63.6 88.4 68.7] for val in np.nditer(meas): print(val) -> 1.73 1.68 1.71 1.89 1.79 65.4 59.2 63.6 88.4 68.7
Recap
Dictionary : for key, val in my_dict.items() :
Numpy array : for val in np.nditer(my_array) :
Pandas
for first try
import pandas as pd brics = pd.read_csv("brics.csv", index_col = 0) country capital area population BR Brazil Brasilia 8.516 200.40 RU Russia Moscow 17.100 143.50 IN India New Delhi 3.286 1252.00 CH China Beijing 9.597 1357.00 SA South Africa Pretoria 1.221 52.98 for val in brics : print(val) -> country capital area population
Iterrows
for lab, row brics.iterrows() print(lab) print(row) -> BR country Brazil capital Brasilia area 8.516 population 200.4 Name: BR, dtype: object (..)
Selective print
for lab, row brics.iterrows() print(lab + ": " + row["capital"]) -> BR: Brasilia RU: Moscow IN: New Delhi CH: Beijing SA: Pretoria
Add a column to the data frame :
for lab, row brics.iterrows() brics.loc[lab, "name_length"] = len( row["country"]) print(brics) -> country capital area population name_length BR Brazil Brasilia 8.516 200.40 6 RU Russia Moscow 17.100 143.50 6 IN India New Delhi 3.286 1252.00 5 CH China Beijing 9.597 1357.00 5 SA South Africa Pretoria 1.221 52.98 12
With using apply :
brics["name_length"] = brics["country"].apply(len)
From the exercices :
# 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) #In one line with apply, upper is a method so you need to use #a slightly different syntax cars['COUNTRY'] = cars["country"].apply(str.upper)