02 04 Loops - HannaAA17/Data-Scientist-With-Python-datacamp GitHub Wiki
# 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 var in seq:
expression
# 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))
# 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" )
for c in "family":
print(c.capitalize())
Dictionary
for
key,val in my_dict.items():
Numpy array
for val in np.nditer(my_array):
# 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)
# 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)
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
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)