Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
def do_stuff_with_number(n):
    print(n)

def catch_this():
    the_list = (1, 2, 3, 4, 5)

    for i in range(20):
        try:
            do_stuff_with_number(the_list[i])
        except IndexError: # Raised when accessing a non-existing index of a list
            do_stuff_with_number('out of bound - %d' % i)

catch_this()


Numpy

Convert arrays to Numpy arrays

Code Block
# Create 2 new lists height and weight
height = [1.87,  1.87, 1.82, 1.91, 1.90, 1.85]
weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]

# Import the numpy package as np
import numpy as np

# Create 2 numpy arrays from height and weight
np_height = np.array(height)
np_weight = np.array(weight)

print(type(np_height))

# Calculate bmi
bmi = np_weight / np_height ** 2

# Print the result
print(bmi)

# For a boolean response
print(bmi > 23)

# Print only those observations above 23
print(bmi[bmi > 23])

Result

Code Block
<class 'numpy.ndarray'>
[ 23.34925219  27.88755755  28.75558507  25.48723993  23.87257618
  25.84368152]
[ True  True  True  True  True  True]
[ 23.34925219  27.88755755  28.75558507  25.48723993  23.87257618
  25.84368152]


Convert all of the weights from kilograms to pounds based in NumPy

Code Block
weight_kg = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]

import numpy as np

# Create a numpy array np_weight_kg from weight_kg
np_weight_kg = np.array(weight_kg)

# Create np_weight_lbs from np_weight_kg
np_weight_lbs = np_weight_kg * 2.2

# Print out np_weight_lbs
print(np_weight_lbs)

Result

Code Block
    [ 179.63   214.544  209.55   204.556  189.596  194.59 ]


Pandas DataFrame / CSV / Join / Merge

...