I am working on the file "Objects and Data Structures/Print Formatting.ipynb".
The first task is:
Percent Notation with Strings, Floats, and Integers
You can format your printing using percent notation. Recall, we use the following notation for various types:
Strings: %s
Integers: %d
Float: %f
Can you write Python code for it?

s = "this is a string"

print("Well, %s" % (s))


I am working on the file "Objects and Data Structures/Print Formatting.ipynb".
The first task is:
Print Function Revamped
The Python 3 print function is notated in the documentation as the following:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Let's see what "sep" means.
Can you write Python code for it?

# Normal print
print("hello")

# Utilizing the "sep" parameter by simply adding multiple object arguments
print("hello", "there")


I am working on the file "Objects and Data Structures/Sets.ipynb".
The first task is:
A call to clear() on a set deletes all of its objects.
Can you write Python code for it?

# Clear a Set
yoz_set.clear()
# Verify
print(yoz_set)


I am working on the file "Objects and Data Structures/Sets.ipynb".
The first task is:
Fear not - no errors or exceptions are raised when adding items that already exist in a set, they are just considerd by the set once. While the cell does not accurately represent this, we can print and verify.
Can you write Python code for it?

# A set with non-unique elements?
my_set = {"Hello", "Hello", 9.0, 9.0}
# Verifying that the set only considered each item once
print(my_set)


I am working on the file "Objects and Data Structures/Sets.ipynb".
The first task is:
Notice how all of the objects in the set we made are unique. What if we make a set like this?
Can you write Python code for it?

# A set with non-unique elements?
my_set = {"Hello", "Hello", 9.0, 9.0}


I am working on the file "Objects and Data Structures/Sets.ipynb".
The first task is:
The add() method adds an item to a set (mutator).
Can you write Python code for it?

# Add an object to our set
yoz_set.add("Blocky")
# Verify
print(yoz_set)


I am working on the file "Objects and Data Structures/Sets.ipynb".
The first task is:
The copy() method returns a copy of the set object. It allows the programmer to quickly replicate the object distinctly (not object reference).
Can you write Python code for it?

# Recreate yoz_set
yoz_set = {"Temple Run", "2048", "Fruit Ninja", "Crossy Road"}
# Copy and save the set
my_second_yoz_set = yoz_set.copy()
# Verify
print(my_second_yoz_set)


I am working on the file "Objects and Data Structures/Sets.ipynb".
The first task is:
The difference() method returns the objects that make a set different from the implicit parameter.
implicit_set.difference(explicit_set)

Returns objects from the implicit_set that do not exist in the explicit set.
Can you write Python code for it?

# Create a set
my_set = {"woo", "foo"}
# Create another set
my_2_set = {"rsoos", "dja"}
# Difference
my_set.difference(my_2_set)


I am working on the file "Objects and Data Structures/Sets.ipynb".
The first task is:
The discard(object) method removes an object from the set. If object is not in set, nothing is removed.
Can you write Python code for it?

# Create a Set
yoz_set = {"Temple Run", "2048", "Fruit Ninja", "Crossy Road"}
# Discard "Fruit Ninja"
yoz_set.discard("Fruit Ninja")
# Verify that "Fruit Ninja" is gone from set
print(yoz_set)


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
Below is an example where you define the variables at run-time of the print function
The format is similar:
my_str.format(var1=somevalue, var2=....)
Can you write Python code for it?

print("I've got {x} problems, and programming in python ain't {my_str}".format(x=99, my_str="one"))


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
Below, we use the my_str.split() method on my_str. The split method takes each contigous sequence, or word, instead of an overall string and puts each words inside of a data structure called a list. A list is a mutable, indexable sequence of objects in Python. We'll talk about it more later, but, for now, imagine it just holds objects (basically anything) together in a bundle.
Can you write Python code for it?

# split a string
lst = my_str.split()
print(lst)


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
Escape Sequences
You may be wondering if it's possible to print more than one string (or sentence) with a single print function. This is entirely possible with the "escape sequence". An escape sequence is a character set that allows us to print characters that we normally couldn't. For example, how could you create new lines in your escape sequence? Let's try writing an email.
Can you write Python code for it?

print("To whom it may concern,\n\nI'm currently in a Python Bootcamp right now and I'm starting to hone my skills.\n\nBest,\nMohsin")


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
How would we reverse a string? We know that the start would be the end, the end would be the start. By default, our skip moves forward by "1". We found out earlier could change this to "-1" to go backwards. If we can automatically go backwards, do we need a start or and end if the indexing will stop itself? No! Consider:
my_str[::-1]

to reverse a string.
Can you write Python code for it?


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
However, we can do two things to strings: concatenation and physical reassignment
That's right, while you can't single handedly change a character of your string instance, you can concatenate characters to it or reassign it to whatever string you want. The reason this is allowed is because strings can be physically reassigned into new sequences (words), but not changed on the spot.
Can you write Python code for it?

# Reassigning a string to whatever we want
my_str = "black labs"

# Reassign again
my_str = "parrots"


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
It printed "c", we expected this, becuase 0 is like the number 1 in our everyday lives. Computer systems start with 0. How would we get the last character of a string? We could just count the words in our string and subtract 1.
Thought process: the length of "crabs" is 5. We know that the last character is at 5-1 = 4 because we start with the number 0 in indexing. So, theoretically, my_str[4] should return the last character of "crabs", which woiuld be 's'.
Can you write Python code for it?


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
Note how the interpreter returned: TypeError: 'str' object does not support item assignment
String's cannot be physically changed this way. You cannot pick an indice and change it's character. Look, it doesn't work:
Can you write Python code for it?


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
Printing Strings
Recall that in the Numbers notebook, we decided that printing was preferred over using the REPL. This is becuase in all code you write, you will never use the REPL alone, as printing is necessary. We print strings by calling the print function.
Can you write Python code for it?

# Printing a string
print("Hey, there!")

# Printing another string in the same cell, not possible with just the REPL!
print("Hey, there... again!")


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
So, what kind of function is this? Well, because this function works under a built-in object type in python (the number types), this is called a function. It's not a built-in function, because we made it ourselves. In short, we can classify functions and methods into 4 categories:
1. Built-in functions (https://docs.python.org/3/library/functions.html)
    > These are already with Python
2. Programmer created functions (even_or_odd which is above)
    > These functions are associated with Python's built-in objects like numbers, strings, etc.
3. Programmer created methods (an example later)
    > These methods (which are a tier below functions) are associated with programmer created objects. We haven't created an object yet but when we do, we will defined functions that work with our custom objects. Those functions are known as methods.

So what functions and methods to Strings have?
Back to the point: strings have a few functions associated with them also. The one you should know is the len() function. It returns the length of a string.
len() function
Can you write Python code for it?

# The len function
len("hello")

# We can print the result of the len() function
print(len("Hello"))

# Let's store it in variable form
length_of_some_string = len("Hello")
# now print whatever len("Hello") returns
print(length_of_some_string)


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
String Methods
String methods are those functions that are associated with a specific string instance, where are as string functions are concerned with strings as a whole. Note: the word instance refers to the objectifying of anything in Python or another language that has objects in it.
Can you write Python code for it?

# Creating a string instance is just the same thing as assigning a variable a value
c = "Hello"


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
String Properties
What properties to strings have? Well, we said earlier strings are indexable. We already talked about that. We also said that strings were "immutable". To be immutable means to not be able to be changed. A string literal within a variable cannot be altered by indexing. Take a look:
Can you write Python code for it?


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
There are a few more escape sequences. Note that there is no need to memorize them, as you can just look them up and they will become second nature over time as you need them. View them on Microsoft's Developer Network article: https://msdn.microsoft.com/en-us/library/h21280bw.aspx
String Functions and Methods
You might be wondering, what's difference between a function and a method? What is a function? What is a method? Technically, all methods ARE functions. Methods are functions that belong to objects (remember, everything is essentially an object in Python). Functions in Python can either be defined by you, the programmer or are already defined by the Python developers, which are called "Built-in Functions". These are functions you can call impromptu and they'll just work. Here are some examples of built-in functions.
Can you write Python code for it?

# The built-in float function takes in an integer and returns a float -> float(integer_here)
my_integer = 4
my_float = float(my_integer)
print(my_float)


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
This is called using the the "str %" construct. This construct allows us to substitute the %letter with any variable want. For integers, it's %d, %f for float, and %s for string.
Can you write Python code for it?

my_str = "hello"
print("%s, it's me" % my_str)

pi_val = 3.140000
print("I think pi is around %f" % pi_val)

# You can add multiple arguments
x = 5
y = "hello"
print("%s it's me, I was wondering how you've been these past %d months" % (y, x))


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
Watch out for the format() function in the printing section at the bottom.
Indexing and Slicing Strings
Strings, as we defined before, are indexable. Effectively, this means you can access the individual characters that make up a string. How do we do this? We begin by using the bracket notation and specify an index between 0 to the length of the string - 1. Let n be the length of the string, then we can access a string as such:
my_string_here[0]
my_string_here[1]
.
.
.
my_string_here[n-1]

Let's try declaring some strings and finding the start, end, middle, etc.
Can you write Python code for it?

# Declare a string
my_str = "crabs"

# Find the beginning of a string is simply index 0
print(my_str[0])


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
We just printed a multi-line message with one print function. Here, we used the newline escape sequence, called with "\n". The \n tells the interpreter to skip a line (aka create a new line). This allowed us to make our text look like an email. We can use two \n in a row, as we did above. This applies to all other escape sequences. There are a few others you should know, including the tab escape sequence, which namely allows you to use tabs in your print functions.
Can you write Python code for it?

# Tab escape sequence
print("\t<-- Look at that space!")


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
What if we wanted more than just one character? How about the first character all the way to the second to last character? This process is called slicing. We can slice strings to get ranges of their characters. Let's get the first to second last.
In general, slicing works like so:
my_str[start:end]

where "start" is inclusive, and "end" is exclusive.
Thought process: to get the first to second last, where the "end" of a slicing is not included, would simply mean let start be 0, and end be the length of the string minus 1 (becuase it's the character we don't want.
Can you write Python code for it?

# Get the first to second to last character.
my_str[0:len(my_str)-1]


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
What just happened? Remember that we said that slicing works like so:
my_str[start(inclusive):end(exclusive)]

Thus, if we want the very first string, we let start be 0. For the end, we put in the index of the character we don't want included up until. Meaning that if we don't want the last character, we put the indice of the character as end. That indice that represents the last character is n-1, where n represents length of the string. We reduce to this formula:
my_str[0:lengthofstring - 1]

How do we get the length? Recall: the len() built-in function. We call the function to get the length, and subtract by 1 to get
my_str[0:len(my_str)-1]

which yields a satisfying "crab" instead of "crabs".
There's a shortcut for getting from any start to the definite end of a string (ex: get all characters starting from 3rd to the very end, get all characters from the 2nd character to then very end). Simply leave out the end argument and fill in the start with an indice you want to start and include.
my_str[start:]
Can you write Python code for it?

# go from the 2nd character to the end
print(my_str[2:])


I am working on the file "Objects and Data Structures/Strings.ipynb".
The first task is:
What we saw above is an example of a Built-in FUNCTION. These come with Python. We can also define our own functions/methods. Below, we are defining a function that tells you if a number is even or odd.
Can you write Python code for it?

def even_or_odd(some_number):
    if some_number % 2 == 0:
        return True


I am working on the file "Objects and Data Structures/Tuples.ipynb".
The first task is:
All structures that can use slicing (sequences... i.e. strings, tuples, lists) have skips. Recall the general notation for slicing.
my_sequence[start:end:skip]

where "start" is inclusive, end is exclusive, and skip is the sequence traversal factor.
Can you write Python code for it?

# Getting every other object in a Tuple
print(day_tuple[::2])

# Getting the tuple objects backward
print(day_tuple[::-1])


I am working on the file "Objects and Data Structures/Tuples.ipynb".
The first task is:
Because tuples and lists are sequences, we cannot search by some "key". Only mappings can perform actions like these naturally (we have a way to do this, in the methods section). A tuple semantically acts the same as a list, and as you are already familiar with a list, can perform slicing.
Can you write Python code for it?

# Getting all of the items in a tuple using slicing
print(day_tuple[0:])


I am working on the file "Objects and Data Structures/Tuples.ipynb".
The first task is:
Here is an example of a heterogenous tuple. Recall that are definable types in Python are objects, and thus even data structures like lists and dictionaries can be the items of a tuple. On the flipside, tuples can act as a key and a value in a dictionary! This is because all keys in a dictionary must be hashable, and tuples are. Tuples can also be objects in lists.
Can you write Python code for it?

# Initializing a heterogenous Tuple
my_tuple = ("red", 40, 9.0, [1, 4, 5], "hey", {"Micah":9})


I am working on the file "Objects and Data Structures/Tuples.ipynb".
The first task is:
No form of modification on an already existing tuple object will work, whether is appending, prepending, etc. Only reassignment.
Tuple Functions and Methods
There are a few functions and methods associated with tuples. We explore them below.
Tuple Functions
As always, we know that the len() function works on tuples.
Can you write Python code for it?


I am working on the file "Objects and Data Structures/Tuples.ipynb".
The first task is:
Now that we've seen accessing by normal bracket notation and slicing, let's discuss modification. Tuples are immutable sequences, meaning that they cannot be changed in place. What does this mean exactly? Like strings, tuples can physically change what they are referring to but they cannot change the obejcts that are in them in place.
Can you write Python code for it?

# Intializing a Tuple
day_tuple = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY")
# Attempt to change an item via access bracket notation
day_tuple[1] = "SUNDAY"


I am working on the file "Objects and Data Structures/Tuples.ipynb".
The first task is:
The index(object) methods finds the first occurence of the explicit object, and returns the indice.
Can you write Python code for it?

# Initializing a Tuple (with ony one WEDNESDAY string literal)
day_tuple = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY")
# Return the index of Wednesday
day_tuple.index("WEDNESDAY")
# Reassign the tuple to another object
day_tuple = ("WEDNESDAY", "TUESDAY", "WEDNESDAY", "FRIDAY", "WEDNESAY")
# What index will it return now that are 3 "WEDNESDAY" string literals
day_tuple.index("WEDNESDAY")


I am working on the file "Objects and Data Structures/Tuples.ipynb".
The first task is:
Tuple Access, Slicing, and Modification
You can access any item in a tuple with bracket notation.
Can you write Python code for it?

# Initializing a Tuple
day_tuple = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY")
# Access Thursday
print(day_tuple[3])


I am working on the file "Observations_seaice.ipynb".
The first task is:
Determine hysteresis settings
Can you write Python code for it?

signal = 1/sb[3]

## quartiles

signalarray = np.asarray(signal).reshape(-1)
signal_no0 = np.ma.masked_equal(signalarray,0)
signal_no0=signal_no0.compressed()

#np.percentile(signal_no0, [25, 50, 75, 100])

## There is no control data for observations => must choose thresholds based on data itself.
# Here, use 75 and 50%ile (quartiles 2 and 3)

upper_threshold=np.percentile(signal_no0, 95)
lower_threshold=np.percentile(signal_no0, 50)

from hyper_canny import cp_edge_thinning, cp_double_threshold

# use directions of pixel based sobel transform and magnitudes from calibrated physical sobel.
dat = pixel_sb.transpose([3,2,1,0]).astype('float32')
dat[:,:,:,3] = sb[3].transpose([2,1,0])
mask = cp_edge_thinning(dat)
thinned = mask.transpose([2, 1, 0])
dat = sb.transpose([3,2,1,0]).copy().astype('float32')

edges = cp_double_threshold(data=dat, mask=mask, a=1/upper_threshold, b=1/lower_threshold)
m = edges.transpose([2, 1, 0])

years = np.array([d.year for d in box.dates])
my_cmap = matplotlib.cm.get_cmap('rainbow')  #YlGnBu
my_cmap.set_under('w')
plot_orthographic_np(box, (years[:,None,None]*m).max(axis=0),  cmap=my_cmap, vmin=1979)


I am working on the file "Observations_seaice.ipynb".
The first task is:
Load the data
Can you write Python code for it?

from datetime import date, timedelta

box = data_set.box

print("({:.6~P}, {:.6~P}, {:.6~P}) per pixel".format(*box.resolution))
for t in box.time[:3]:
    print(box.date(t), end=', ')
print(" ...")

dt = box.time[1:] - box.time[:-1]
print("time steps: max", dt.max(), "min", dt.min())


I am working on the file "Observations_seaice.ipynb".
The first task is:
Smoothing
Smoothing in the lattitudinal direction (N-S) is not affected by the projection; distances do not vary since the circles of equal longitude are all greater circles on the sphere. We apply a Gaussian filter where we reflect data in the lattitudinal and time directions and wrap in the longitudinal direction. Next, to filter in the longitudinal direction, we need to use a different filter width for each lattitude.
Can you write Python code for it?

yearly_data_set = data_set
box = yearly_data_set.box
data = yearly_data_set.data

smooth_data = gaussian_filter(box, data, [sigma_t, sigma_d, sigma_d])

my_cmap = matplotlib.cm.get_cmap('rainbow')  #YlGnBu
my_cmap.set_under('w')

plot_orthographic_np(box, yearly_data_set.data[0], cmap=my_cmap, vmin=0.1) #1979

plot_orthographic_np(box, yearly_data_set.data[28], cmap=my_cmap, vmin=0.1) #2007

plot_orthographic_np(box, yearly_data_set.data[33], cmap=my_cmap, vmin=0.1) #2012

plot_orthographic_np(box, yearly_data_set.data[36], cmap=my_cmap, vmin=0.1) #2015


I am working on the file "Observations_seaice.ipynb".
The first task is:
Sobel filtering
The Sobel filter has the same problem as the Gaussian filter, but the solution is easier. We just correct for the magnitude of the Sobel response by multiplying the longitudinal component by the cosine of the latitude.
Can you write Python code for it?

sb = sobel_filter(box, smooth_data, weight=sobel_weights)
pixel_sb = sobel_filter(box, smooth_data, physical=False)


I am working on the file "October 13th 2017 - Intro to Python/Lesson 1/Chapter 1 - Reading from a CSV.ipynb".
The first task is:
1.1 Reading data from a csv file
You can read data from a CSV file using the read_csv function. By default, it assumes that the fields are comma-separated.
We're going to be looking some cyclist data from Montréal. Here's the original page (in French), but it's already included in this repository. We're using the data from 2012.
This dataset is a list of how many people were on 7 different bike paths in Montreal, each day.
Can you write Python code for it?

broken_df = pd.read_csv('../data/bikes.csv')

# Look at the first 3 rows
broken_df[:3]


I am working on the file "October 13th 2017 - Intro to Python/Lesson 1/Chapter 1 - Reading from a CSV.ipynb".
The first task is:
1.2 Selecting a column
When you read a CSV, you get a kind of object called a DataFrame, which is made up of rows and columns. You get columns out of a DataFrame the same way you get elements out of a dictionary.
Here's an example:
Can you write Python code for it?


I am working on the file "October 13th 2017 - Intro to Python/Lesson 1/Chapter 1 - Reading from a CSV.ipynb".
The first task is:
1.3 Plotting a column
Just add .plot() to the end! How could it be easier? =)
We can see that, unsurprisingly, not many people are biking in January, February, and March,
Can you write Python code for it?


I am working on the file "October 13th 2017 - Intro to Python/Lesson 1/Chapter 1 - Reading from a CSV.ipynb".
The first task is:
1.4 Putting all that together
Here's the code we needed to write do draw that graph, all together:
Can you write Python code for it?

df = pd.read_csv('../data/bikes.csv', sep=';', encoding='latin1', parse_dates=['Date'], dayfirst=True, index_col='Date')
df['Berri 1'].plot()


I am working on the file "October 13th 2017 - Intro to Python/Lesson 1/Chapter 1 - Reading from a CSV.ipynb".
The first task is:
You'll notice that this is totally broken! read_csv has a bunch of options that will let us fix that, though. Here we'll

change the column separator to a ;
Set the encoding to 'latin1' (the default is 'utf8')
Parse the dates in the 'Date' column
Tell it that our dates have the date first instead of the month first
Set the index to be the 'Date' column
Can you write Python code for it?

fixed_df = pd.read_csv('../data/bikes.csv', sep=';', encoding='latin1', parse_dates=['Date'], dayfirst=True, index_col='Date')
fixed_df[:3]


I am working on the file "October 23, 2016/Studio Solution.ipynb".
The first task is:
Solution with only Number
Can you write Python code for it?

"""
Studio: Holiday
"""

# get input: departure day (0-6) and duration
departure_day = input("Which day are you leaving on? (0=Sun, 1=Mon, etc)")
departure_day = int(departure_day)

duration = input("How many days will you be done?")
duration = int(duration)

# calculate return day and respond
return_day = (departure_day + duration) % 7
print("You will return on day", return_day)


I am working on the file "October 27, 2016/Covered in class.ipynb".
The first task is:
Chapter 4 Exercises
Bottles of beer
Can you write Python code for it?

bottles_of_beer = 99

for bottle_number in range(bottles_of_beer, 0, -1):
    print(bottle_number, "Bottles of Beer on the Wall")
    print("Take one down pass it around")


I am working on the file "October 27, 2016/Covered in class.ipynb".
The first task is:
Fun with Turtles
Can you write Python code for it?

import turtle
wn = turtle.Screen()        # creates a graphics window
alex = turtle.Turtle()      # create a turtle named alex
alex.speed(1)
alex.shape('turtle')

for i in [0,1,2,3,4,5]:
    alex.forward(150)           # tell alex to move forward by 150 units
    alex.left(85)               # turn by 90 degrees
    alex.forward(75)

## This won't run as expected with the notebook. Wait a moment for the window to be created.

wn.exitonclick()


I am working on the file "October 27, 2016/Covered in class.ipynb".
The first task is:
Lots of turtles
Can you write Python code for it?

import turtle
wn = turtle.Screen()
wn.bgcolor("lightgreen")
tess = turtle.Turtle()
tess.color("blue")
tess.shape("turtle")

jim = turtle.Turtle()
jim.color("green")
jim.shape("turtle")

carl = turtle.Turtle()
carl.color("red")
carl.shape("turtle")

tess.up()
carl.up()
jim.up()
# Keep in mind for today's studio
for size in range(5, 60, 2):    # start with size = 5 and grow by 2
    tess.stamp()                # leave an impression on the canvas
    carl.stamp()
    jim.stamp()

    carl.forward(size + 10)
    jim.forward(size)
    tess.forward(size)          # move tess along

    carl.right(90)
    jim.left(24)
    tess.right(24)              # and turn her

wn.exitonclick()


I am working on the file "October 27, 2016/done-in-class.ipynb".
The first task is:
Chapter 4 Exercises
Bottles of beer
Can you write Python code for it?

number_of_beers = 99

for number in range(number_of_beers, 0, -1):
    print(number, "bottles of beer on the walll", number,"bottles of beer on the wall take one down pass it around")
    print(number - 1, "bottles of beer on the wall")


I am working on the file "October 27, 2016/done-in-class.ipynb".
The first task is:
Draw the regular polygon
Write a program that asks the user for the number of sides, the length of the side, the color, and the fill color of a regular polygon. The program should draw the polygon and then fill it in.
Can you write Python code for it?

import turtle
wn = turtle.Screen()
alex = turtle.Turtle()

sides_number = int(input("How many sides?"))
sides_length = int(input("How long are the sides?"))
line_color = input("What color for the lines?")
fill_color = input("What color for the fill?")

alex.color(line_color)
alex.fillcolor(fill_color)

alex.speed(1)
alex.begin_fill()

for i in range(sides_number):
    alex.forward(sides_length)
    alex.left((360)/(sides_number))

alex.end_fill()


I am working on the file "October 27, 2016/done-in-class.ipynb".
The first task is:
Fun with Turtles
Can you write Python code for it?


I am working on the file "October 27, 2016/done-in-class.ipynb".
The first task is:
Looking at documentation for tutles
The documentation for the module inside of Python can be found here:
https://docs.python.org/3.6/library/turtle.html
Can you write Python code for it?

# Copied from the documentation example. This is bad practice to do import * DO NOT DO IT!
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break
end_fill()
done()


I am working on the file "October 27, 2016/done-in-class.ipynb".
The first task is:
Lots of turtles
Can you write Python code for it?


I am working on the file "October 27, 2016/done-in-class.ipynb".
The first task is:
Random
Remember how it's not actually random. Here is an example:
Can you write Python code for it?

import random

random.seed(5)

print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10), '\n')

random.seed(15)

print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10), '\n')

random.seed(22)

print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10), '\n')

# Setting the seed back to 5 you can observe that it will always have the same results
random.seed(5)

print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10), '\n')


I am working on the file "October 27, 2016/done-in-class.ipynb".
The first task is:
Studio: Donut
Show them a random Donut of the day: "Yellow Jacket - creme, sugar, and honey with a glazed top and cake body"
Ask the patron how much they want to pay per donut?
Ask the number of donuts they want to buy? (fractional donuts)
Take into account the tax rate: 5%
python
    >>> "Here's the donut of the day"
    >>> "Yellow Jacket - creme, sugar, and honey with a glazed top and cake body"
    >>> "How many donuts?"
    >>> "What do you want to pay per donut?"
    >>> "Computing price...."
    >>> "You shall pay: $price$"
Can you write Python code for it?


I am working on the file "October 27, 2016/done-in-class.ipynb".
The first task is:
Using Range
Can you write Python code for it?

for i in [6, 5, 4, 3]:
    print("I have", i, "cookies.  I'm going to eat one.")

print('I ate all my cookies')


I am working on the file "Odds to win.ipynb".
The first task is:
0.633... as a score is not that bad, a little bit better than a blind guess.
To know if your prediction model is good or not, all you have to do is compare with blind guesses. This case we have only two possible outcomes, either a victory to team purple or victory to team blue, 50-50! Now we have a model that predicts correclty 63.3% of the games.
We saw in the confusion matrix that our model is predicting much more victories to Blue Team over the Purple Team, which shows some bias towards onf of the teams, this may be corrected adding more features or maybe normalizing them (to be tried some other day).
Also this bias is what is damaging our model, because it can correctly predicts 60% of the games won by the Blue Team, but less than 70% of the games won by purple team. So, if we blind guess "Blue Team Win" 100% of the time, will we score a higher "correct rate" than using the model?
The answer should be "no", but we are dealing with a skill game, not a pure random one, therefore there must be important features left behind to make the prediction a better one (thinking of addind the champions chosen by each team)

We have 20 victories by Blue Team and 10 victories by Purple Team
Total of 30 games
Can you write Python code for it?

Blue_Team_Win = 20
Purple_Team_Win = 10

total_games = Purple_Team_Win + Blue_Team_Win
All_Blue_Bets = (100 / total_games) * Blue_Team_Win
All_Purple_Bets = (100 / total_games) * Purple_Team_Win

print ("Team Blue won:", All_Blue_Bets, "%")
print ("Team Purple won:", All_Purple_Bets, "%")


I am working on the file "Odds to win.ipynb".
The first task is:
Loading up the data of the LCS SPRING 2016 tournament
Fatures:

MPB/MPP = Match Points Blue/Purple
MR = Match Result (B = Blue won, P = Purple won)
TRB/TRP = Team Rank Blue/Purple
FRR = First Round Result (B/P)
RB/RP = Rating of team Blue/Purple
W10B/W10P = Wins in the last 10 months team Blue/Purple
L10B/L10P = Losses in the last 10 months team Blue/Purple
HWB/HWP = Historic Wins by Blue/Purple against this opponent
GBB/GBP = GosuBet on Blue/Purple
BO = Best of 1, 3 or 5
url = url of the match
Can you write Python code for it?

dta = pd.read_csv('data/lol-2016/lcs-s-16.csv', parse_dates=[1])
dta


I am working on the file "Odds to win.ipynb".
The first task is:
Now the feature columns are setted so we can use it to train the machine-learning algorithm
Can you write Python code for it?


I am working on the file "Odds to win.ipynb".
The first task is:
Now we are finally ready to use the data to train the algorithm. First an AdaBoostClassifier object is created, and here we need to give supply a set of arguments for it to work properly. The first argument is classification algoritm to use, which is the DecisionTreeClassifier algorithm. I have chosen to supply this algorithms with the max_dept=3 argument, which constrains the training algorithm to not apply more than three rules before making a prediction.
The n_estimators argument tells the algorithm how many decision trees it should fit, and the learning_rate argument tells the algorithm how much the misclassified matches are going to be up-weighted in the next round of decision three fitting. These two values are usually something that you can experiment with since there is no definite rule on how these should be set. The rule of thumb is that the lower the learning rate is, the more estimators you neeed. Actually there is way more to it, because if it is too large, it will miss the local minimum, if it is too low it will take FOREVER to reach the minimum.
The last argument, random_state, is a random seed. It is necessary if you want to reproduce the model fitting exactly every time. If this is not specified you will end up with slightly different trained algroithm each time you fit them.
At last the algorithm is fitted using the fit() method, which is supplied with the odds and match results.
Can you write Python code for it?

from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier

adb = AdaBoostClassifier(
    DecisionTreeClassifier(max_depth=3),
    n_estimators=1000,
    learning_rate=0.4, random_state=42)

adb = adb.fit(feature_train, results_train)


I am working on the file "Odds to win.ipynb".
The first task is:
Scoring our model visualizing the data
Ok, first thing we are going to do is run a score that will evaluate our model. There are many ways to evaluate it, but the simple "score" method shown here is good enough for this model that we are dealing with. (Others would be F1 and accuracy.)
Also important is to be able to see the prediction in the data, view each "game result" according to our model and compare with its real outcomes.
Can you write Python code for it?


I am working on the file "Odds to win.ipynb".
The first task is:
Separating the data for training and for test
Can you write Python code for it?

train_idx = np.array(dta.data < '2016-02-27') #year month day
test_idx = np.array(dta.data >= '2016-02-27') #year month day

results_train = np.array(dta.MR[train_idx])
results_test = np.array(dta.MR[test_idx])
print("Training set:", len(results_train), "Test set:", len(results_test))
dta[test_idx]


I am working on the file "Odds to win.ipynb".
The first task is:
The PR column
Now we add the Prediction column to the data (and drop the URL column because it takes too much view space)
The Prediction column will be declared as PR and must show the predicted outcome for a given match.
Can you write Python code for it?

pd.options.mode.chained_assignment = None

test_data['PR'] = np.array(adb.predict(feature_test))
try:
    test_data = test_data.drop('url', 1)
except:
    pass

test_data.sort('data', ascending=True)


I am working on the file "Odds to win.ipynb".
The first task is:
We can now see how well the trained algorithm fits the training data.
Can you write Python code for it?

import sklearn.metrics as skm
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix

training_pred = adb.predict(feature_train)
print (skm.confusion_matrix(list(training_pred), list(results_train)))


I am working on the file "Odds to win.ipynb".
The first task is:
We see that no matches in the training data are misclassified, usually this is not very good because it may imply that we have an overfitted model with poor predictive power on new data. This problem may be solved by tweaking features and adding more data.
Yeah, it may sound strange, but something that predicts 100% of accuracy the training data may actually be a bad thing.
Let’s try to predict the outcome of the LCS-Sprint 2016 from march to the end of the tournament.
Can you write Python code for it?

import matplotlib.pyplot as plt

test_pred = adb.predict(feature_test)
labels = ['Blue Team', 'Purple Team']

y_test = results_test
y_pred = test_pred

def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(labels))
    plt.xticks(tick_marks, labels, rotation=45)
    plt.yticks(tick_marks, labels)
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

# Compute confusion matrix
cm = confusion_matrix(y_test, y_pred)
np.set_printoptions(precision=2)
print('Confusion matrix, without normalization')
print(cm)
plt.figure()
plot_confusion_matrix(cm)

# Normalize the confusion matrix by row (i.e by the number of samples
# in each class)
cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print('Normalized confusion matrix')
print(cm_normalized)
plt.figure()
plot_confusion_matrix(cm_normalized, title='Normalized confusion matrix')

plt.show()


I am working on the file "Off Center Ring Simulation.ipynb".
The first task is:
Make a helper function to run the simulation
Can you write Python code for it?

def ring_audio_synthesis(num_speakers, radius, head_pos, frequencies, synthesis='phasor'):
    VirtualAngles = np.expand_dims(np.linspace(-np.pi, np.pi, 8*num_speakers, endpoint=False),axis=1)
    VirtualDistance = radius # This is a fixed assumption!!!
    VirtualAmp = 1 # This is a fixed assumption

    LR_Distances = [left_ear_distance(VirtualAngles, radius, head_pos),
                right_ear_distance(VirtualAngles, radius, head_pos)]

    DesiredSounds = [np.abs(wave_eq(VirtualAmp, LR_Distances[0], frequencies)),
                np.abs(wave_eq(VirtualAmp, LR_Distances[1], frequencies))]

    SynthAngle = virtual_source_angle(VirtualAngles, num_speakers, radius)
    SynthAmp = virtual_source_amplitude(VirtualAngles, radius,
        SynthAngle[0], SynthAngle[1], frequencies, head_pos, synthesis=synthesis)

    LeftDistances = [left_ear_distance(s, radius, head_pos) for s in SynthAngle]
    RightDistances = [right_ear_distance(s, radius, head_pos) for s in SynthAngle]

    SynthesizedSounds = [
        np.abs(wave_eq(SynthAmp[0], LeftDistances[0], frequencies) + \
            wave_eq(SynthAmp[1], LeftDistances[1], frequencies)),
        np.abs(wave_eq(SynthAmp[0], RightDistances[0], frequencies) + \
            wave_eq(SynthAmp[1], RightDistances[1], frequencies))
    ]

    SynthesizedSoundAtCenter = np.abs(wave_eq(SynthAmp[0], LR_Distances[0], frequencies) + \
            wave_eq(SynthAmp[1], LR_Distances[1], frequencies))

    return VirtualAngles, LR_Distances, DesiredSounds, SynthAngle, SynthAmp, \
           [LeftDistances, RightDistances], SynthesizedSounds, SynthesizedSoundAtCenter


I am working on the file "Off Center Ring Simulation.ipynb".
The first task is:
Synthetic speaker amplitudes for virtual sources
Next, we want to generate the amplitude that each of our two closest
speakers should be driven at. In free space, the sound that reaches the ear
will fall off in amplitude by 1/distance to the ear. We'll use the center
of the head as our target point and will match the synthesized amplitude
to what the virtual source would have created at that point. (We don't try
to match phase!). More complicatedly, speaking of phase, we need to be aware
of the fact that because the two speakers are different distances from the
ear, it's possible that their signal will combine destructively. So ideally,
we'd scale them to make sure that their sum has the right amplitude.
In order to do this, we will use 3 methods.
  - "Closest": This will just drive the closest speaker, with amplitude scaled
        by distance
  - "Naive": This will just scale the amplitude of the sound
        based on the relative angle between the virtual source and the
        two speakers.
  - "Phasor": This will take into account the relative phase of the signals.
Can you write Python code for it?

def cos_triangle_rule(x1, x2, phi):
# Really useful formula for finding the length of a vector difference when you
# know the lengths of the two arguments and the angle between them.
# In other words, return ||A - B||, where phi is the angle between them,
# and ||A|| = x1 and ||B|| = x2.
    return np.sqrt(x1**2 + x2**2 - 2*x1*x2*np.cos(phi))

def virtual_source_amplitude(virtual_angle, radius, source1_angle, source2_angle,
        freq, head_x=0, speed_of_sound=343.0, synthesis='phasor'):
#  We assume that the virtual source is on a ring with the given radius, and
#  that the head is positioned at the vertical center, and horizontally displaced
#  by head_x. The amplitude is equally split between the two given sources
#  based on their relative distance from the virtual source.
#  NOTE: source angles are measured clockwise from vertical axis, but head is displaced
#    in the horizontal axis
#  Finally, we assume the virtual amplitude is 1. Everything scales with that

    virtual_angle = np.mod(virtual_angle, 2*np.pi)  # make angles between 0 and 2pi
    source1_angle = np.mod(source1_angle, 2*np.pi)
    source2_angle = np.mod(source2_angle, 2*np.pi)

    virtual_distance = cos_triangle_rule(radius, head_x, np.pi/2 - virtual_angle)
    source1_distance = cos_triangle_rule(radius, head_x, np.pi/2 - source1_angle)
    source2_distance = cos_triangle_rule(radius, head_x, np.pi/2 - source2_angle)

    dAngle = np.minimum(np.abs(source2_angle-source1_angle), # Angle between sources. Note that this assumes
        np.abs(2*np.pi - (source2_angle-source1_angle)))     #  they are adjacent!

    angularDistance = np.minimum(np.abs(virtual_angle - source1_angle), # Take into account wrapping
            np.abs(2*np.pi - (virtual_angle - source1_angle)))

    source1_relative_angle = 1 - angularDistance/dAngle # Want amplitude to be large (close to 1)
    source2_relative_angle = 1 - source1_relative_angle #   for closest source, source1

    if synthesis=='phasor':
        omega = 2*np.pi*freq
        k = omega /...


I am working on the file "Off Center Ring Simulation.ipynb".
The first task is:
Virtual sources
Virtual sources are sounds that come from a location between two speakers.
We will synthesize their sound using the two nearest speakers.
Next, let's find the nearest two speakers for an arbitrary virtual angle.
Subsequent code requires that the first speaker returned be the closest,
so be extra careful!
Important note: Our reference for virtual source angles is "north"
(in front of the nose), going clockwise.
Can you write Python code for it?

def virtual_source_angle(virtual_angle, num_speakers, radius):
    speaker_angles = np.linspace(0, 2*np.pi, num_speakers, endpoint=False)
    speaker_angles = np.expand_dims(speaker_angles,axis=0)
    virtual_angle = np.mod(virtual_angle, 2*np.pi)  # make angles between 0 and 2pi
    dist_mat = np.minimum(np.abs(virtual_angle - speaker_angles),
        np.abs(2*np.pi - (virtual_angle - speaker_angles)) )
    ClosestSourceAngle = np.take(speaker_angles, np.argmin(dist_mat, axis=1))
    if (virtual_angle.ndim > 0):
        ClosestSourceAngle = np.expand_dims(ClosestSourceAngle,1)

    dist_mat2 = dist_mat
    for rowidx, row in enumerate(dist_mat):
        dist_mat2[rowidx, row.argmin()] = np.inf
    NextClosestSourceAngle = np.take(speaker_angles, np.argmin(dist_mat2, axis=1))
    if (virtual_angle.ndim > 0):
        NextClosestSourceAngle = np.expand_dims(NextClosestSourceAngle,1)

    return  [ClosestSourceAngle, NextClosestSourceAngle]


I am working on the file "Office Football Pool (2015).ipynb".
The first task is:
Data description
We have data from the 2008-2014 seasons. I pulled it from Wikipedia because
every other source basically restricts use. The data sets used in this webinare are
also in the repository.

Season, Week, and Date
Team and Opponent
Points and PointsAllowed, for the Team and Opponent respectively
Stadium (sometimes)
Overtime (a string with the number of periods of overtime, otherwise Null)
AtHome
True if the game is at home (or in London but the team is the 'Home' team)
False for the superbowl, for both teams

VegasSpread, VegasTotal, VegasWin
The betting details from before the game. Donated by TipRanks.com

Interceptions, Sacks, Fumbles, PenaltyYards
Also donated by TipRanks.com
Interceptions: interceptions thrown
Fumbles: fumbles made (not fumbles forced)
Sacks: sacks made by the defense

There are two rows per game, one for the home team and one for the away team, so that we can do aggregations over a team (like a moving average of total points allowed).
Can you write Python code for it?

##
# Transformations using Pandas

# Spread
#    The pandas.DataFrame uses numpy arrays to enable array-wise operations.
df['Spread'] = df.Points - df.PointsAllowed

# PtsPct
df['PointsPercent'] = df.Points / (df.Points + df.PointsAllowed)

# Outcome
#    When assigning to a subset of a column in a DataFrame,
#    use indexing ('ix' or other functions) to identify the subset.
df['Outcome'] = np.nan  # pre-fill the column
df.ix[df.Spread > 0, 'Outcome'] = 'W'
df.ix[df.Spread < 0, 'Outcome'] = 'L'
df.ix[df.Spread == 0, 'Outcome'] = 'T'

# WLT (record)
#    Make sure the data are sorted.
#    Then:
#    Use 'apply' for user-defined functions
#    and 'cumsum' for a running sum; rows with np.nan
#    in the outcome will just add zero
df = df.sort(['Team','Season','Week'])
df['WLT'] = df.groupby(['Team','Season'])['Outcome'].apply(
    lambda o:
        (o == 'W').cumsum().astype(str) + '-' +
        (o == 'L').cumsum().astype(str) + '-'+
        (o == 'T').cumsum().astype(str) )

# WinPct
df['WinPct'] = df.groupby(('Team','Season'))['Spread'].apply(
    lambda s: (0.5 * (s == 0).cumsum() + (s > 0).cumsum()) / s.notnull().cumsum() )

# LastWkBye
#    Make sure the data are sorted.
#    Then flag whether last game was a Bye
df = df.sort(['Team', 'Season','Week'])
df['LastWeekBye'] = df.groupby(['Team','Season'])['Spread'].shift(1).isnull().fillna(False)
df.ix[df.Week == 1, 'LastWeekBye'] = False

# Past5WkAvgPts
#    Make sure the data are sorted.
#    Then use the windowing functions
#    see: http://pandas.pydata.org/pandas-docs/stable/computation.html
#    window size = 5, minimum required observations = 2
df = df.sort(['Team','Season', 'Week'])
df['Past5WkAvgPts'] = df.groupby(['Team']).Points.apply(
    pd.rolling_mean, window=5, min_periods=2).shift(1)

# Past5WkAvgFumbles
#    Some of the sorting seems unnecessary
#    but is good in case you copy and paste a snippet elsewhere...
df = df.sort(['Team','Season','Week'])
df['Past5WkAvgFumbles'] = df.groupby(['Team']).Fumbles.apply(
    pd.rolling_mean,...


I am working on the file "Office Football Pool (2015).ipynb".
The first task is:
For the confidence pool
Rank teams by likelihood that they will win. Highest total wins.
- 1 point = lowest confidence
- highest points = highest confidence
For this we don't want a class output, we want a probability:
- model.decision_function(input_data) or
- model._predict_proba(input_data)
It is this decision function that is used to draw the
Receiver Operating Curve (ROC plot):
Can you write Python code for it?

##
# ROC charts
# http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html
from sklearn.metrics import roc_curve, auc

fig, axs = plt.subplots(2, 3, sharey=True)
fig.set_size_inches(12, 8)

for (ax, (name, model)) in zip(axs.flatten(), models.items()):
    try:
        fpr, tpr, _ = roc_curve(win[test], model.predict_proba(input_data[test])[:,1])
    except:
        fpr, tpr, _ = roc_curve(win[test], model.decision_function(input_data[test]))
    roc_auc = auc(fpr, tpr)
    ax.plot(fpr, tpr, label='ROC curve\n(area = {:0.2f})'.format(roc_auc))
    ax.plot((0,0), (1,1), ls="--", c=".3", color='lightgray')  # Diagonal line 1=1
    ax.set_xlim([0.0, 1.0])
    ax.set_ylim([0.0, 1.05])
    ax.legend(loc='lower right', fontsize=12, frameon=False)
    if ax.is_first_col():
        ax.set_ylabel('True Positive Rate')
    ax.set_xticks([])
    ax.set_xlabel('False Positive Rate')
    ax.set_title(name)

plt.show()


I am working on the file "Office Football Pool (2015).ipynb".
The first task is:
OK, Jupyter
If you haven't seen this format before, it is a Jupyter notebook. It runs a web GUI that sends code , grouped in 'cells', to a listening interpreter to execute, then displays the results. Usually you do this on your own computer, but there's a way to serve notebooks too. Jupyter notebooks are good for interactive demos like this and for executable reports.

Start it on the command line by typing ipython notebook in a directory above your notebooks, or else from the Anaconda Launcher, click ipython-notebook
The project is written in Python but can execute code for anything that has a "kernel" — a way to receive code and send responses. We are using the IPython kernel, and there's one built for R, Ruby, Haskell, and others (reference).
The extra %matplotlib inline above is a 'magic', a meta-command not part of Python that instructs Jupyter to perform inline plotting.
Can you write Python code for it?

# Evaluate this cell for documentation on Jupyter magics
%magic


I am working on the file "Office Football Pool (2015).ipynb".
The first task is:
Or we can look at a particular team / teams
The year-over-year median scores can be read as "half of the games had at least that spread"...because the median is the value of the middle item if they were sorted.
Can you write Python code for it?

fig = plt.figure()
ax = plt.subplot(111)

tmp = df[df.Team.isin(['Chicago Bears','Detroit Lions','Denver Broncos'])
        ].groupby(['Team', 'Season']
           ).Spread.median().unstack().transpose()
tmp.plot(ax=ax, lw=3, figsize=(12,4), legend=False)

plt.xlabel('Season')
plt.ylabel('Median Spread')

# Shrink current axis by 20% to make room for the annotation
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])

# Legend to the right of the current axis
ax.annotate('... Manning?',(2012, tmp.ix[2012,'Denver Broncos']), xytext=(2010.2, 10.5),
             arrowprops=dict(arrowstyle='->'))
ax.annotate('... Suh?',(2010, tmp.ix[2012,'Detroit Lions']), xytext=(2010, -11),
             arrowprops=dict(arrowstyle='->'))

for y, txt in zip([-7,7,2],
                  ['Chicago Bears', 'Denver Broncos', 'Detroit Lions']):
    ax.annotate(txt, (2014, y), xytext=(2014.1, y))

plt.title("It's a team sport, but...")
plt.show()


I am working on the file "Office Football Pool (2015).ipynb".
The first task is:
Pandas I/O
Read a CSV file with the function pd.read_csv. The other input options are:
Can you write Python code for it?

##
# Pro tip:
#    You probably know 'help(object)' will show documentation for the object.
#    'dir(object)' will list all names accessible via the object.
print(' '.join([x for x in dir(pd) if 'read_' in x]))

## ... and output options:
print(' '.join([x for x in dir(pd.DataFrame) if 'to_' in x]))

import os  # in case you're on windows
file_location = os.path.join('data', 'nfl_season2008to2014.csv')
df = pd.read_csv(file_location)

df.head(3)


I am working on the file "Office Football Pool (2015).ipynb".
The first task is:
Takeaway: Pandas data manipulation

Arraywise arithmetic (via numpy)
apply functions for custom functions over columns or rows (also see transform)
Moving windows, with time shift
Groupby for operations on grouped subsets
Subsetting via masks, e.g. df.ix[df.Spread > 0, 'Outcome'] = 'W'
Inspection via df.head(), df.tail(), df['column'].value_counts, df.describe()

Plotting
The Pandas documentation labelled visualization is better than the plotting documentation.
Since it's based on matplotlib they leave details to the
matplotlib plotting docs.
Can you write Python code for it?

##
# Distribution of the point spread
#
plt.subplot(221)
df.Spread.plot(kind='density')
plt.title('Spread 2008-2014')
plt.xlim((-60,60))
plt.gcf().set_size_inches(12, 5)

plt.subplot(222)
df.Spread.hist(bins=60)
plt.title('...but not many ties')

plt.subplot(212)
plt.plot(df.Spread, df.index, 'ko', alpha=0.1)
plt.xlabel('All games')

plt.show()

##
# Spread distribution by year
#   -- demonstrates pandas.DataFrame.pivot_table
#
df[['Week', 'Team', 'Season','Spread']].pivot_table(
    index=['Week', 'Team'], columns='Season', values='Spread').hist(
    bins=25, layout=(2,4), figsize=(12,3.5), sharey=True)
plt.show()

##
# Or cumulative distribution of spread
#    Uses the same 'hist' function as above but with different keyword arguments.
#
df.Spread.hist(cumulative=True, normed=True, histtype='step', bins=100, figsize=(9,4))
#- The shape is consistent season-over-season. If you want to see that uncomment the below....
#df.groupby('Season').Spread.hist(cumulative=True, normed=True, histtype='step', bins=100, figsize=(9,4))

plt.title('Cumulative Spread Distribution, NFL 2008-2014')
plt.ylim(0,1)
plt.xlabel('Spread')
plt.ylabel('Percent of Teams below Spread')
plt.axvline(x=7, hold=None, color='lightblue', linewidth=3)
plt.axvline(x=14, hold=None, color='lightblue', linewidth=2)
plt.axvline(x=21, hold=None, color='lightblue', linewidth=1)
plt.show()

##
# We can do things like explore whether home field advantage exists.
#
df[['AtHome', 'Spread']].boxplot(by='AtHome', figsize=(7,4))
plt.suptitle('')
plt.title('Difference in spread for Home vs Away teams')
plt.ylabel('Spread'); plt.xlabel('Playing at Home?')
plt.show()

##
# ... by Win counts now
fig = plt.figure()
ax = plt.subplot(111)

pd.crosstab(df.AtHome, df.Outcome).plot(
    ax=ax, kind='barh', stacked=True,
    color=['red','blue', 'green'], figsize=(9,5))

# Mom says label your axes
plt.ylabel('At Home?'); plt.xlabel('Number of Outcomes')

# Shrink current axis by 20% to make room for the legend
box = ax.get_position()
ax.set_position([box.x0,...


I am working on the file "Office Football Pool (2015).ipynb".
The first task is:
Try out some regression models
As an R user, scikit-learn's consistent API is really a delight.
The lack of diagnostics are bothersome — but in this new 'data science' world it looks like we don't care about scrutinizing the model so long as the cross-validations hold up. Ha. The simple API means switching models is as simple as changing a class name, and the actual documentation is detailed enough to describe when to use which models.
We won't tune the models here but sklearn.grid_search provides an api that will exhaustively explore a user-specified grid of (model-specific) tuning parameters.
To show the versatility of the api, we are using
- Linear regression
    + Least squares (minimize distance between actual and prediction)
    + Ridge  (add a penalty to pull coefficients toward zero)
- Regression tree (try to handle the nonlinearity and discrete results)
- Ensemble methods (there are other ones than just trees)
    + Random forest
    + Gradient boosting
- Support vector machine (had no idea this could be for something other than classification)
Can you write Python code for it?

##
# Some popular regression models
from sklearn import ensemble
from sklearn import linear_model
from sklearn import svm
from sklearn import tree

# To see available tuning settings are for a model,
# call help on its initialization function, e.g. :
#  help(linear_model.Ridge.__init__)
models = dict(
    ols = linear_model.LinearRegression(),
    gbm = ensemble.GradientBoostingRegressor(max_depth=5),
    ridge = linear_model.Ridge(),
    svr = svm.LinearSVR(epsilon=2),
    tree = tree.DecisionTreeRegressor(max_depth=5),
    random_forest = ensemble.RandomForestRegressor(n_estimators=5, max_depth=5)
)

rmses = {}
for name, model in models.items():
    rmses[name] = perform_kfold_cross_validation(model, input_data, spread, k=8)

pd.DataFrame(rmses).boxplot(vert=False, return_type='axes')
plt.gcf().set_size_inches(9, 5)
plt.xlabel("Error in predicted spread"); plt.ylabel("Model")
plt.show()

fig, axs = plt.subplots(2, 3, sharey=True)
fig.set_size_inches(12, 8)

# Make the train/test split be pre-2014/2014
train = games[no_nulls].Season < 2014
test = games[no_nulls].Season == 2014

for (ax, (name, model)) in zip(axs.flatten(), models.items()):
    model.fit(input_data.ix[train], spread[train])
    ax.scatter(x=spread[test], y=model.predict(input_data.ix[test]), alpha=0.2)
    ax.plot((-60,60), (-60,60), ls="--", c=".3", color='gray')  # Diagonal line 1=1
    ax.set_title(name)
    ax.set_ylim(-30,30)
    ax.set_ylabel('Predicted')

plt.show()


I am working on the file "OkNLP-model.ipynb".
The first task is:
Cross-Validated Estimates
Logistic Regression, naive Bayes, SVM, Random Forest
Can you write Python code for it?

clf0 = LogisticRegression()
clf1 = MultinomialNB()
clf2 = LinearSVC()
clf3 = RandomForestClassifier()

for clf, name in zip([clf0, clf1, clf2, clf3],
                     ['Logistic Regression', 'naive Bayes', 'SVM', 'Random Forest']):
    yhat = cross_val_predict(clf, X, y, cv=10)
    print("Accuracy: %0.4f [%s]" % (accuracy_score(y, yhat), name))

print("""Without feature selection:

Accuracy: 0.6715 [Logistic Regression]
Accuracy: 0.6738 [naive Bayes]
Accuracy: 0.6387 [SVM]
Accuracy: 0.6305 [Random Forest]""")


I am working on the file "OkNLP-model.ipynb".
The first task is:
Log Odds Ratio features
Can you write Python code for it?

count_0 = count_matrix[np.array(drugs.drugs=='yes'), :].sum(axis=0)
count_1 = count_matrix[np.array(drugs.drugs=='no'), :].sum(axis=0)
counts = np.array(np.vstack((count_0, count_1)))
log_odds = log_odds_ratio(counts, vocab, use_variance=True)

n = 2000
top = log_odds.sort('log_odds_ratio', ascending=False)['features'].tolist()[:n]
bottom = log_odds.sort('log_odds_ratio', ascending=False)['features'].tolist()[-n:]
log_odds_features = top + bottom

log_odds_mask = np.array([t in log_odds_features for t in vocab])

X = X[:,log_odds_mask]


I am working on the file "OkNLP-model.ipynb".
The first task is:
Models
Featurize
Can you write Python code for it?

y = drugs.y.values #1/0 vector

X = tfidf_matrix.copy()


I am working on the file "OkNLP-model.ipynb".
The first task is:
Subsample
Can you write Python code for it?

df_4_y = df_4[df_4.drugs == 'yes'] #take only users with yes/no drug status
df_4_n = df_4[df_4.drugs == 'no']

df_4_y = df_4_y.sample(6500, random_state=42) #subsample data for both y and no
df_4_n = df_4_n.sample(6500, random_state=42)

drugs = df_4_y.append(df_4_n) #combine dfs

drugs['y'] = drugs['drugs'].apply(lambda x: 1 if x == 'yes' else 0) #add column for 1/0 if drug use


I am working on the file "Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb".
The first task is:
Average Every 10 Sec During ROP Exam for first 4 minutes
Can you write Python code for it?

#AVERAGE DURING ROP EXAM FOR FIRST FOUR MINUTES
def perdelta1(start, end, delta):
    r1 = []
    curr = start
    while curr < end:
        r1.append(curr)
        curr += delta
    return r1

df1PI = df_clean.PI[X:X+timedelta(minutes=4)]
df1O2 = df.SpO2[X:X+timedelta(minutes=4)]
df1PR = df.PR[X:X+timedelta(minutes=4)]
win1 = timedelta(seconds=10) #any unit of time & make the range

r1 = perdelta1(X, X+timedelta(minutes=4), win1)

#make the series to store
avg1PI = Series(index = r1, name = 'PI DurEx')
avg1O2 = Series(index = r1, name = 'SpO2 DurEx')
avg1PR = Series(index = r1, name = 'PR DurEX')
#average!
for i1 in r1:
    avg1PI[i1] = df1PI[i1:(i1+win1)].mean()
    avg1O2[i1] = df1O2[i1:(i1+win1)].mean()
    avg1PR[i1] = df1PR[i1:(i1+win1)].mean()

result1 = concat([avg1PI, avg1O2, avg1PR], axis=1, join='inner')
print result1


I am working on the file "Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb".
The first task is:
Average Every 15 Mins Hour 2-3 After ROP Exam
Can you write Python code for it?

#AVERAGE EVERY 15 MINUTES TWO HOURS AFTER ROP EXAM

def perdelta3(start, end, delta):
    r3 = []
    curr = start
    while curr < end:
        r3.append(curr)
        curr += delta
    return r3

# datetime(year, month, day, hour, etc.)

df3PI = df_clean.PI[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))]
df3O2 = df.SpO2[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))]
df3PR = df.PR[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))]
win3 = timedelta(minutes=15) #any unit of time, make the range

r3 = perdelta3((Z+timedelta(hours=1)), (Z+timedelta(hours=2)), win3)

#make the series to store
avg3PI = Series(index = r3, name = 'PI q15MinHr2')
avg3O2 = Series(index = r3, name = 'O2 q15MinHr2')
avg3PR = Series(index = r3, name = 'PR q15MinHr2')

#average!
for i3 in r3:
    avg3PI[i3] = df3PI[i3:(i3+win3)].mean()
    avg3O2[i3] = df3O2[i3:(i3+win3)].mean()
    avg3PR[i3] = df3PR[i3:(i3+win3)].mean()

result3 = concat([avg3PI, avg3O2, avg3PR], axis=1, join='inner')
print result3


I am working on the file "Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb".
The first task is:
Average Every 30 Mins Hour 3-4 After ROP Exam
Can you write Python code for it?

#AVERAGE EVERY 30 MINUTES THREE HOURS AFTER ROP EXAM

def perdelta4(start, end, delta):
    r4 = []
    curr = start
    while curr < end:
        r4.append(curr)
        curr += delta
    return r4

# datetime(year, month, day, hour, etc.)

df4PI = df_clean.PI[(Z+timedelta(hours=2)):(Z+timedelta(hours=3))]
df4O2 = df.SpO2[(Z+timedelta(hours=2)):(Z+timedelta(hours=3))]
df4PR = df.PR[(Z+timedelta(hours=2)):(Z+timedelta(hours=3))]
win4 = timedelta(minutes=30) #any unit of time, make the range

r4 = perdelta4((Z+timedelta(hours=2)), (Z+timedelta(hours=3)), win4)

#make the series to store
avg4PI = Series(index = r4, name = 'PI q30MinHr3')
avg4O2 = Series(index = r4, name = 'O2 q30MinHr3')
avg4PR = Series(index = r4, name = 'PR q30MinHr3')

#average!
for i4 in r4:
    avg4PI[i4] = df4PI[i4:(i4+win4)].mean()
    avg4O2[i4] = df4O2[i4:(i4+win4)].mean()
    avg4PR[i4] = df4PR[i4:(i4+win4)].mean()

result4 = concat([avg4PI, avg4O2, avg4PR], axis=1, join='inner')
print result4


I am working on the file "Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb".
The first task is:
Average Every 5 Mins Hour 1-2 After ROP Exam
Can you write Python code for it?

#AVERAGE EVERY 5 MINUTES ONE HOUR AFTER ROP EXAM

def perdelta2(start, end, delta):
    r2 = []
    curr = start
    while curr < end:
        r2.append(curr)
        curr += delta
    return r2

# datetime(year, month, day, hour, etc.)

df2PI = df_clean.PI[Z:(Z+timedelta(hours=1))]
df2O2 = df.SpO2[Z:(Z+timedelta(hours=1))]
df2PR = df.PR[Z:(Z+timedelta(hours=1))]
win2 = timedelta(minutes=5) #any unit of time, make the range

r2 = perdelta2(Z, (Z+timedelta(hours=1)), win2) #define the average using function

#make the series to store
avg2PI = Series(index = r2, name = 'PI q5MinHr1')
avg2O2 = Series(index = r2, name = 'O2 q5MinHr1')
avg2PR = Series(index = r2, name = 'PR q5MinHr1')

#average!
for i2 in r2:
    avg2PI[i2] = df2PI[i2:(i2+win2)].mean()
    avg2O2[i2] = df2O2[i2:(i2+win2)].mean()
    avg2PR[i2] = df2PR[i2:(i2+win2)].mean()

result2 = concat([avg2PI, avg2O2, avg2PR], axis=1, join='inner')
print result2


I am working on the file "Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb".
The first task is:
Average Every Hour 4-24 Hours Post ROP Exam
Can you write Python code for it?

#AVERAGE EVERY 60 MINUTES 4-24 HOURS AFTER ROP EXAM

def perdelta5(start, end, delta):
    r5 = []
    curr = start
    while curr < end:
        r5.append(curr)
        curr += delta
    return r5

# datetime(year, month, day, hour, etc.)

df5PI = df_clean.PI[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))]
df5O2 = df.SpO2[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))]
df5PR = df.PR[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))]
win5 = timedelta(minutes=60) #any unit of time, make the range

r5 = perdelta5((Z+timedelta(hours=3)), (Z+timedelta(hours=24)), win5)

#make the series to store
avg5PI = Series(index = r5, name = 'PI q60MinHr4+')
avg5O2 = Series(index = r5, name = 'O2 q60MinHr4+')
avg5PR = Series(index = r5, name = 'PR q60MinHr4+')

#average!
for i5 in r5:
    avg5PI[i5] = df5PI[i5:(i5+win5)].mean()
    avg5O2[i5] = df5O2[i5:(i5+win5)].mean()
    avg5PR[i5] = df5PR[i5:(i5+win5)].mean()

result5 = concat([avg5PI, avg5O2, avg5PR], axis=1, join='inner')
print result5


I am working on the file "Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb".
The first task is:
Average q 5 Min for 1 hour after 1st Eye Drops
Can you write Python code for it?

# Every 5 min Average from start of eye drops to start of exam

def perdeltadrop(start, end, delta):
    rdrop = []
    curr = start
    while curr < end:
        rdrop.append(curr)
        curr += delta
    return rdrop

dfdropPI = df_clean.PI[W:W+timedelta(hours=1)]
dfdropO2 = df.SpO2[W:W+timedelta(hours=1)]
dfdropPR = df.PR[W:W+timedelta(hours=1)]
windrop = timedelta(minutes=5)#make the range
rdrop = perdeltadrop(W, W+timedelta(minutes=15), windrop)

avgdropPI = Series(index = rdrop, name = 'PI DurEyeD')
avgdropO2 = Series(index = rdrop, name = 'SpO2 DurEyeD')
avgdropPR = Series(index = rdrop, name = 'PR DurEyeD')

for i in rdrop:
    avgdropPI[i] = dfdropPI[i:(i+windrop)].mean()
    avgdropO2[i] = dfdropO2[i:(i+windrop)].mean()
    avgdropPR[i] = dfdropPR[i:(i+windrop)].mean()

resultdrops = concat([avgdropPI, avgdropO2, avgdropPR], axis=1, join='inner')
print resultdrops


I am working on the file "Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb".
The first task is:
Baseline Averages
Can you write Python code for it?

avg0PI = df_clean.PI[Y:W].mean()
avg0O2 = df.SpO2[Y:W].mean()
avg0PR = df.PR[Y:W].mean()

print 'Baseline Averages\n', 'PI :\t',avg0PI, '\nSpO2 :\t',avg0O2,'\nPR :\t',avg0PR,
#df.std() for standard deviation


I am working on the file "Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb".
The first task is:
Import File into Python
Change File Name!
Can you write Python code for it?

df = pd.read_csv('/Users/John/Dropbox/LLU/ROP/Pulse Ox/ROP018PO.csv',
            parse_dates={'timestamp': ['Date','Time']},
            index_col='timestamp',
            usecols=['Date', 'Time', 'SpO2', 'PR', 'PI', 'Exceptions'],
            na_values=['0'],
            converters={'Exceptions':  readD}
            )

#parse_dates tells the read_csv function to combine the date and time column
#into one timestamp column and parse it as a timestamp.
#    pandas is smart enough to know how to parse a date in various formats

#index_col sets the timestamp column to be the index.

#usecols tells the read_csv function to select only the subset of the columns.
#na_values is used to turn 0 into NaN

#converters: readD is the dict that means any string with 'C' with be NaN (for PI)

#dfclean = df[27:33][df[27:33].loc[:, ['SpO2', 'PR', 'PI', 'Exceptions']].apply(pd.notnull).all(1)]
#clean the dataframe to get rid of rows that have NaN for PI purposes
df_clean = df[df.loc[:, ['PI', 'Exceptions']].apply(pd.notnull).all(1)]

"""Pulse ox date/time is 1 mins and 32 seconds faster than phone. Have to correct for it."""

TC = timedelta(minutes=1, seconds=32)


I am working on the file "Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb".
The first task is:
Set Date and Time of ROP Exam and Eye Drops
Can you write Python code for it?

df_first = df.first_valid_index() #get the first number from index

Y = pd.to_datetime(df_first) #convert index to datetime
# Y = TIME DATA COLLECTION BEGAN / First data point on CSV

# SYNTAX:
# datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

W = datetime(2016, 1, 20, 7, 30)+TC
# W = first eye drop dtarts
X = datetime(2016, 1, 20, 8, 42)+TC
# X = ROP Exam Started
Z = datetime(2016, 1, 20, 8, 46)+TC
# Z = ROP Exam Ended

df_last = df.last_valid_index() #get the last number from index

Q = pd.to_datetime(df_last)

# Q = TIME DATA COLLECTION ENDED / Last Data point on CSV


I am working on the file "Old Code/EyeDrops160223.ipynb".
The first task is:
Baseline Average Calculation
Can you write Python code for it?

avg0NIRS = df.StO2[Y:W1].mean()
avg0PI = df.PI[Y:W1].mean()
avg0O2 = df.SpO2[Y:W1].mean()
avg0PR = df.PR[Y:W1].mean()

print 'Baseline Averages\n', 'NIRS :\t', avg0NIRS, '\nPI :\t',avg0PI, '\nSpO2 :\t',avg0O2,'\nPR :\t',avg0PR,
#df.std() for standard deviation


I am working on the file "Old Code/EyeDrops160223.ipynb".
The first task is:
First Eye Drop Avg Every 10 Sec For 5 Minutes
Can you write Python code for it?

def perdeltadrop1(start, end, delta):
    rdrop1 = []
    curr = start
    while curr < end:
        rdrop1.append(curr)
        curr += delta
    return rdrop1

dfdrop1NI = df.StO2[W1:W1+timedelta(minutes=5)]
dfdrop1PI = df.PI[W1:W1+timedelta(minutes=5)]
dfdrop1O2 = df.SpO2[W1:W1+timedelta(minutes=5)]
dfdrop1PR = df.PR[W1:W1+timedelta(minutes=5)]
windrop1 = timedelta(seconds=10)

rdrop1 = perdeltadrop1(W1, W1+timedelta(minutes=5), windrop1)

avgdrop1NI = Series(index = rdrop1, name = 'StO2 1st ED')
avgdrop1PI = Series(index = rdrop1, name = 'PI 1st ED')
avgdrop1O2 = Series(index = rdrop1, name = 'SpO2 1st ED')
avgdrop1PR = Series(index = rdrop1, name = 'PR 1st ED')

for i in rdrop1:
    avgdrop1NI[i] = dfdrop1NI[i:(i+windrop1)].mean()
    avgdrop1PI[i] = dfdrop1PI[i:(i+windrop1)].mean()
    avgdrop1O2[i] = dfdrop1O2[i:(i+windrop1)].mean()
    avgdrop1PR[i] = dfdrop1PR[i:(i+windrop1)].mean()

resultdrops1 = concat([avgdrop1NI, avgdrop1PI, avgdrop1O2, avgdrop1PR], axis=1, join='inner')
print resultdrops1


I am working on the file "Old Code/EyeDrops160223.ipynb".
The first task is:
Second Eye Drop Avg Every 10 Sec For 5 Minutes
Can you write Python code for it?

def perdeltadrop2(start, end, delta):
    rdrop2 = []
    curr = start
    while curr < end:
        rdrop2.append(curr)
        curr += delta
    return rdrop2

dfdrop2NI = df.StO2[W2:W2+timedelta(minutes=5)]
dfdrop2PI = df.PI[W2:W2+timedelta(minutes=5)]
dfdrop2O2 = df.SpO2[W2:W2+timedelta(minutes=5)]
dfdrop2PR = df.PR[W2:W2+timedelta(minutes=5)]
windrop2 = timedelta(seconds=10)

rdrop2 = perdeltadrop2(W2, W2+timedelta(minutes=5), windrop2)

avgdrop2NI = Series(index = rdrop2, name = 'StO2 2nd ED')
avgdrop2PI = Series(index = rdrop2, name = 'PI 2nd ED')
avgdrop2O2 = Series(index = rdrop2, name = 'SpO2 2nd ED')
avgdrop2PR = Series(index = rdrop2, name = 'PR 2nd ED')

for i in rdrop2:
    avgdrop2NI[i] = dfdrop2NI[i:(i+windrop2)].mean()
    avgdrop2PI[i] = dfdrop2PI[i:(i+windrop2)].mean()
    avgdrop2O2[i] = dfdrop2O2[i:(i+windrop2)].mean()
    avgdrop2PR[i] = dfdrop2PR[i:(i+windrop2)].mean()

resultdrops2 = concat([avgdrop2NI, avgdrop2PI, avgdrop2O2, avgdrop2PR], axis=1, join='inner')
print resultdrops2


I am working on the file "Old Code/EyeDrops160223.ipynb".
The first task is:
Third Eye Drop Avg Every 10 Sec For 5 Minutes
Can you write Python code for it?

def perdeltadrop3(start, end, delta):
    rdrop3 = []
    curr = start
    while curr < end:
        rdrop3.append(curr)
        curr += delta
    return rdrop3

dfdrop3NI = df.StO2[W3:W3+timedelta(minutes=5)]
dfdrop3PI = df.PI[W3:W3+timedelta(minutes=5)]
dfdrop3O2 = df.SpO2[W3:W3+timedelta(minutes=5)]
dfdrop3PR = df.PR[W3:W3+timedelta(minutes=5)]
windrop3 = timedelta(seconds=10)

rdrop3 = perdeltadrop3(W3, W3+timedelta(minutes=5), windrop3)

avgdrop3NI = Series(index = rdrop3, name = 'StO2 3rd ED')
avgdrop3PI = Series(index = rdrop3, name = 'PI 3rd ED')
avgdrop3O2 = Series(index = rdrop3, name = 'SpO2 3rd ED')
avgdrop3PR = Series(index = rdrop3, name = 'PR 3rd ED')

for i in rdrop3:
    avgdrop3NI[i] = dfdrop3NI[i:(i+windrop3)].mean()
    avgdrop3PI[i] = dfdrop3PI[i:(i+windrop3)].mean()
    avgdrop3O2[i] = dfdrop3O2[i:(i+windrop3)].mean()
    avgdrop3PR[i] = dfdrop3PR[i:(i+windrop3)].mean()

resultdrops3 = concat([avgdrop3NI, avgdrop3PI, avgdrop3O2, avgdrop3PR], axis=1, join='inner')
print resultdrops3


I am working on the file "Old Code/Masimo Analysis - Template150919.ipynb".
The first task is:
Average Every 10 Sec During ROP Exam
Can you write Python code for it?

#AVERAGE PI DURING ROP EXAM
def perdelta(start, end, delta):
    r1_PI = []
    curr = start
    while curr < end:
        r1_PI.append(curr)
        curr += delta
    return r1_PI

df1_PI = df_PI[X:Z]
win1_PI = timedelta(seconds=10) #any unit of time
#make the range
r1_PI = perdelta(X, Z, win1_PI)

#make the series to store
avg1_PI = Series(index = r1_PI, name = 'PI During')

#average!
for i1_PI in r1_PI:
    avg1_PI[i1_PI] = df1_PI[i1_PI:(i1_PI+win1_PI)].mean()

#
#AVERAGE SpO2 DURING ROP EXAM
#
def perdelta(start, end, delta):
    r1_O2 = []
    curr = start
    while curr < end:
        r1_O2.append(curr)
        curr += delta
    return r1_O2

df1_O2 = df_O2[X:Z]
win1_O2 = timedelta(seconds=10) #any unit of time
#make the range
r1_O2 = perdelta(X, Z, win1_O2)

#make the series to store
avg1_O2 = Series(index = r1_O2, name = 'SpO2 During')

#average!
for i1_O2 in r1_O2:
    avg1_O2[i1_O2] = df1_O2[i1_O2:(i1_O2+win1_O2)].mean()

#
#AVERAGE PR DURING ROP EXAM
#
def perdelta(start, end, delta):
    r1_PR = []
    curr = start
    while curr < end:
        r1_PR.append(curr)
        curr += delta
    return r1_PR

df1_PR = df_PR[X:Z]
win1_PR = timedelta(seconds=10) #any unit of time
#make the range
r1_PR = perdelta(X, Z, win1_PR)

#make the series to store
avg1_PR = Series(index = r1_PR, name = 'PR During')

#average!
for i1_PR in r1_PR:
    avg1_PR[i1_PR] = df1_PR[i1_PR:(i1_PR+win1_PR)].mean()
avg1_PR

result1 = concat([avg1_PI, avg1_O2, avg1_PR], axis=1, join='inner')
print result1


I am working on the file "Old Code/Masimo Analysis - Template150919.ipynb".
The first task is:
Average Every 15 Min Hours 2-3 Post ROP Exam
Can you write Python code for it?

#
#AVERAGE PI Q 15 MIN HR 2-3 ROP EXAM
#
def perdelta(start, end, delta):
    r3_PI = []
    curr = start
    while curr < end:
        r3_PI.append(curr)
        curr += delta
    return r3_PI

df3_PI = df_PI[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))]
win3_PI = timedelta(minutes=15) #any unit of time
#make the range
r3_PI = perdelta((Z+timedelta(hours=1)), (Z+timedelta(hours=2)), win3_PI)

#make the series to store
avg3_PI = Series(index = r3_PI, name = 'PI q 15min Hr 2-3')

#average!
for i1_PI in r3_PI:
    avg3_PI[i1_PI] = df3_PI[i1_PI:(i1_PI+win3_PI)].mean()

#
#AVERAGE O2 Q 15 MIN HR 2-3 ROP EXAM
#
def perdelta(start, end, delta):
    r3_O2 = []
    curr = start
    while curr < end:
        r3_O2.append(curr)
        curr += delta
    return r3_O2

df3_O2 = df_O2[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))]
win3_O2 = timedelta(minutes=15) #any unit of time
#make the range
r3_O2 = perdelta((Z+timedelta(hours=1)), (Z+timedelta(hours=2)), win3_O2)

#make the series to store
avg3_O2 = Series(index = r3_O2, name = 'O2 q 15min Hr 2-3')

#average!
for i1_O2 in r3_O2:
    avg3_O2[i1_O2] = df3_O2[i1_O2:(i1_O2+win3_O2)].mean()

#
#AVERAGE PR Q 15 MIN HR 2-3 ROP EXAM
#
def perdelta(start, end, delta):
    r3_PR = []
    curr = start
    while curr < end:
        r3_PR.append(curr)
        curr += delta
    return r3_PR

df3_PR = df_PR[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))]
win3_PR = timedelta(minutes=15) #any unit of time
#make the range
r3_PR = perdelta((Z+timedelta(hours=1)), (Z+timedelta(hours=2)), win3_PR)

#make the series to stPRe
avg3_PR = Series(index = r3_PR, name = 'O2 q 15min Hr 2-3')

#average!
for i1_PR in r3_PR:
    avg3_PR[i1_PR] = df3_PR[i1_PR:(i1_PR+win3_PR)].mean()

result3 = concat([avg3_PI, avg3_O2, avg3_PI], axis=1, join='inner')
print result3


I am working on the file "Old Code/Masimo Analysis - Template150919.ipynb".
The first task is:
Average Every Hour 4-24 Hours Post ROP Exam
Can you write Python code for it?

#
#AVERAGE PI Q HR 4-24 Hrs ROP EXAM
#
def perdelta(start, end, delta):
    r5_PI = []
    curr = start
    while curr < end:
        r5_PI.append(curr)
        curr += delta
    return r5_PI

df5_PI = df_PI[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))]
win5_PI = timedelta(minutes=60) #any unit of time
#make the range
r5_PI = perdelta ((Z+timedelta(hours=3)), (Z+timedelta(hours=24)), win5_PI)

#make the series to store
avg5_PI = Series(index = r5_PI, name = 'PI q 1 Hr 4-24')

#average!
for i1_PI in r5_PI:
    avg5_PI[i1_PI] = df5_PI[i1_PI:(i1_PI+win5_PI)].mean()
avg5_PI

#
#AVERAGE O2 Q HR 4-24 Hrs ROP EXAM
#
def perdelta(start, end, delta):
    r5_O2 = []
    curr = start
    while curr < end:
        r5_O2.append(curr)
        curr += delta
    return r5_O2

df5_O2 = df_O2[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))]
win5_O2 = timedelta(minutes=60) #any unit of time
#make the range
r5_O2 = perdelta ((Z+timedelta(hours=3)), (Z+timedelta(hours=24)), win5_O2)

#make the series to store
avg5_O2 = Series(index = r5_O2, name = 'O2 q 1 Hr 4-24')

#average!
for i1_O2 in r5_O2:
    avg5_O2[i1_O2] = df5_O2[i1_O2:(i1_O2+win5_O2)].mean()
avg5_O2

#
#AVERAGE PR Q HR 4-24 Hrs ROP EXAM
#
def perdelta(start, end, delta):
    r5_PR = []
    curr = start
    while curr < end:
        r5_PR.append(curr)
        curr += delta
    return r5_PR

df5_PR = df_PR[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))]
win5_PR = timedelta(minutes=60) #any unit of time
#make the range
r5_PR = perdelta ((Z+timedelta(hours=3)), (Z+timedelta(hours=24)), win5_PR)

#make the series to store
avg5_PR = Series(index = r5_PR, name = 'PR q 1 Hr 4-24')

#average!
for i1_PR in r5_PR:
    avg5_PR[i1_PR] = df5_PR[i1_PR:(i1_PR+win5_PR)].mean()
avg5_PR

result5 = concat([avg5_PI, avg5_O2, avg5_PI], axis=1, join='inner')
print result5


I am working on the file "Old Code/Masimo Analysis - Template150919.ipynb".
The first task is:
Import File into Python (3 Times)
Change File Name!!
Can you write Python code for it?

df_PI = pd.read_csv('/Users/John/Dropbox/LLU/ROP/Pulse Ox/ROP006PO.csv',
            #Put file path above
            parse_dates={'timestamp': ['Date','Time']},
            index_col='timestamp',
            usecols=['Date', 'Time', 'PI'],
                    na_values=['0'])

df_O2 = pd.read_csv('/Users/John/Dropbox/LLU/ROP/Pulse Ox/ROP006PO.csv',
            #Put file path above
            parse_dates={'timestamp': ['Date','Time']},
            index_col='timestamp',
            usecols=['Date', 'Time', 'SpO2'],
                    na_values=['0'])

df_PR = pd.read_csv('/Users/John/Dropbox/LLU/ROP/Pulse Ox/ROP006PO.csv',
            #Put file path above
            parse_dates={'timestamp': ['Date','Time']},
            index_col='timestamp',
            usecols=['Date', 'Time', 'PR'],
                    na_values=['0'])

# parse_dates tells the read_csv function to combine the date and time column
#     into one timestamp column and parse it as a timestamp.
#     (pandas is smart enough to know how to parse a date in various formats)

# index_col sets the timestamp column to be the index.

# usecols tells the read_csv function to select only the subset of the columns.
# na_values is used to turn 0 into NaN


I am working on the file "Old Code/Masimo Analysis - Template150919.ipynb".
The first task is:
Set Date and Time of ROP Exam
Can you write Python code for it?

df_O2_first = df_O2.first_valid_index() #get the first number from index
Y = pd.to_datetime(df_O2_first) #convert index to datetime
# Y = TIME DATA COLLECTION BEGAN / First data point on CSV

# SYNTAX:
# datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

X = datetime(2015, 6, 17, 8, 36)
# X = ROP Exam Started

Z = datetime(2015, 6, 17, 8, 39)
# Z = ROP Exam Ended

df_O2_last = df_O2.last_valid_index() #get the last number from index
Q = pd.to_datetime(df_O2_last)

# Q = TIME DATA COLLECTION ENDED / Last Data point on CSV


I am working on the file "Old Code/Masimo151111.ipynb".
The first task is:
Average Every 15 Min Hours 2-3 Post ROP Exam
Can you write Python code for it?


I am working on the file "Old Code/Masimo151111.ipynb".
The first task is:
Baseline Average
Can you write Python code for it?

df0_PI = df_PI[Y:X]
avg0_PI = df0_PI.mean()

df0_O2 = df_O2[Y:X]
avg0_O2 = df0_O2.mean()

df0_PR = df_PR[Y:X]
avg0_PR = df0_PR.mean()

print ['Baseline Avgs', avg0_PI, avg0_O2, avg0_PR]


I am working on the file "Old Code/Masimo151111.ipynb".
The first task is:
Export Data out to CSV
Used for fast exporting into Excel and SPSS after tranpose
CHANGE THE FILE NAME!!!!!!!!!!!!!!!!!
Can you write Python code for it?

#export out all averages as a csv file with only

import csv
class excel_tab(csv.excel):
        delimiter = '\t'
csv.register_dialect("excel_tab", excel_tab)

with open('ROP013_POAvgs.csv', 'w') as f:    #CHANGE CSV FILE NAME
    writer = csv.writer(f, dialect=excel_tab)
    writer.writerow(avg0_PI)
    for i1_PI in r1_PI:
        writer.writerow(df1_PI[i1_PI:(i1_PI+win1_PI)].mean())
    for i2_PI in r2_PI:
        writer.writerow(df2_PI[i2_PI:(i2_PI+win2_PI)].mean())
    for i3_PI in r3_PI:
        writer.writerow(df3_PI[i3_PI:(i3_PI+win3_PI)].mean())
    for i4_PI in r4_PI:
        writer.writerow(df4_PI[i4_PI:(i4_PI+win4_PI)].mean())
    for i5_PI in r5_PI:
        writer.writerow(df5_PI[i5_PI:(i5_PI+win5_PI)].mean())
    writer.writerow(avg0_O2)
    for i1_O2 in r1_O2:
        writer.writerow(df1_O2[i1_O2:(i1_O2+win1_O2)].mean())
    for i2_O2 in r2_O2:
        writer.writerow(df2_O2[i2_O2:(i2_O2+win2_O2)].mean())
    for i3_O2 in r3_O2:
        writer.writerow(df3_O2[i3_O2:(i3_O2+win3_O2)].mean())
    for i4_O2 in r4_O2:
        writer.writerow(df4_O2[i4_O2:(i4_O2+win4_O2)].mean())
    for i5_O2 in r5_O2:
        writer.writerow(df5_O2[i5_O2:(i5_O2+win5_O2)].mean())
    writer.writerow(avg0_PR)
    for i1_PR in r1_PR:
        writer.writerow(df1_PR[i1_PR:(i1_PR+win1_PR)].mean())
    for i2_PR in r2_PR:
        writer.writerow(df2_PR[i2_PR:(i2_PR+win2_PR)].mean())
    for i3_PR in r3_PR:
        writer.writerow(df3_PR[i3_PR:(i3_PR+win3_PR)].mean())
    for i4_PR in r4_PR:
        writer.writerow(df4_PR[i4_PR:(i4_PR+win4_PR)].mean())
    for i5_PR in r5_PR:
        writer.writerow(df5_PR[i5_PR:(i5_PR+win5_PR)].mean())


I am working on the file "Old Code/Masimo151111.ipynb".
The first task is:
Import File into Python (3 Times)
Change File Name!!
Can you write Python code for it?

samefile = '/Users/John/Dropbox/LLU/ROP/Pulse Ox/ROP013PO.csv'
#Put file path above

df_PI = pd.read_csv(samefile,
            parse_dates={'timestamp': ['Date','Time']},
            index_col='timestamp',
            usecols=['Date', 'Time', 'PI'],
                    na_values=['0'])

df_O2 = pd.read_csv(samefile,

            parse_dates={'timestamp': ['Date','Time']},
            index_col='timestamp',
            usecols=['Date', 'Time', 'SpO2'],
                    na_values=['0'])

df_PR = pd.read_csv(samefile,

            parse_dates={'timestamp': ['Date','Time']},
            index_col='timestamp',
            usecols=['Date', 'Time', 'PR'],
                    na_values=['0'])

# parse_dates tells the read_csv function to combine the date and time column
#     into one timestamp column and parse it as a timestamp.
#     (pandas is smart enough to know how to parse a date in various formats)

# index_col sets the timestamp column to be the index.

# usecols tells the read_csv function to select only the subset of the columns.
# na_values is used to turn 0 into NaN


I am working on the file "Old Code/Masimo151111.ipynb".
The first task is:
Mild, Moderate, and Severe Desaturation Events
Can you write Python code for it?

df_O2_pre = df_O2[Y:X]

#Find count of these ranges
below = 0 # v <=80
middle = 0 #v >= 81 and v<=84
above = 0 #v >=85 and v<=89
ls = []

b_dict = {}
m_dict = {}
a_dict = {}

for i, v in df_O2_pre['SpO2'].iteritems():

    if v <= 80: #below block

        if not ls:
            ls.append(v)
        else:
            if ls[0] >= 81: #if the range before was not below 80

                if len(ls) >= 5: #if the range was greater than 10 seconds, set to 5 because data points are every 2

                    if ls[0] <= 84: #was it in the middle range?
                        m_dict[middle] = ls
                        middle += 1
                        ls = [v]
                    elif ls[0] >= 85 and ls[0] <=89: #was it in the above range?
                        a_dict[above] = ls
                        above += 1
                        ls = [v]

                else: #old list wasn't long enough to count
                    ls = [v]
            else: #if in the same range
                ls.append(v)

    elif v >= 81 and v<= 84: #middle block

        if not ls:
            ls.append(v)
        else:
            if ls[0] <= 80 or (ls[0]>=85 and ls[0]<= 89): #if not in the middle range
                if len(ls) >= 5: #if range was greater than 10 seconds

                    if ls[0] <= 80: #was it in the below range?
                        b_dict[below] = ls
                        below += 1
                        ls = [v]
                    elif ls[0] >= 85 and ls[0] <=89: #was it in the above range?
                        a_dict[above] = ls
                        above += 1
                        ls = [v]
                else: #old list wasn't long enough to count
                    ls = [v]

            else:
                ls.append(v)

    elif v >= 85 and v <=89: #above block

        if not ls:
            ls.append(v)
        else:
            if ls[0] <=84 : #if not in the above range

                if len(ls) >= 5: #if range was...


I am working on the file "Old Code/Masimo151111.ipynb".
The first task is:
Set Date and Time of ROP Exam
Can you write Python code for it?

df_O2_first = df_O2.first_valid_index() #get the first number from index
Y = pd.to_datetime(df_O2_first) #convert index to datetime
# Y = TIME DATA COLLECTION BEGAN / First data point on CSV

# SYNTAX:
# datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

X = datetime(2015, 10, 14, 9, 36)
# X = ROP Exam Started

Z = datetime(2015, 10, 14, 9, 40)
# Z = ROP Exam Ended

df_O2_last = df_O2.last_valid_index() #get the last number from index
Q = pd.to_datetime(df_O2_last)

# Q = TIME DATA COLLECTION ENDED / Last Data point on CSV


I am working on the file "Old Code/Masimo160127.ipynb".
The first task is:
Average Every 10 Sec During ROP Exam for first 4 minutes
Can you write Python code for it?

#AVERAGE DURING ROP EXAM FOR FIRST FOUR MINUTES
def perdelta1(start, end, delta):
    r1 = []
    curr = start
    while curr < end:
        r1.append(curr)
        curr += delta
    return r1

df1PI = df_clean.PI[X:X+timedelta(minutes=4)]
df1O2 = df.SpO2[X:X+timedelta(minutes=4)]
df1PR = df.PR[X:X+timedelta(minutes=4)]
win1 = timedelta(seconds=10) #any unit of time & make the range

r1 = perdelta1(X, X+timedelta(minutes=4), win1)

#make the series to store
avg1PI = Series(index = r1, name = 'PI DurEx')
avg1O2 = Series(index = r1, name = 'SpO2 DurEx')
avg1PR = Series(index = r1, name = 'PR DurEX')
#average!
for i1 in r1:
    avg1PI[i1] = df1PI[i1:(i1+win1)].mean()
    avg1O2[i1] = df1O2[i1:(i1+win1)].mean()
    avg1PR[i1] = df1PR[i1:(i1+win1)].mean()

result1 = concat([avg1PI, avg1O2, avg1PR], axis=1, join='inner')
print result1


I am working on the file "Old Code/Masimo160127.ipynb".
The first task is:
Average Every 15 Mins Hour 2-3 After ROP Exam
Can you write Python code for it?

#AVERAGE EVERY 15 MINUTES TWO HOURS AFTER ROP EXAM

def perdelta3(start, end, delta):
    r3 = []
    curr = start
    while curr < end:
        r3.append(curr)
        curr += delta
    return r3

# datetime(year, month, day, hour, etc.)

df3PI = df_clean.PI[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))]
df3O2 = df.SpO2[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))]
df3PR = df.PR[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))]
win3 = timedelta(minutes=15) #any unit of time, make the range

r3 = perdelta3((Z+timedelta(hours=1)), (Z+timedelta(hours=2)), win3)

#make the series to store
avg3PI = Series(index = r3, name = 'PI q15MinHr2')
avg3O2 = Series(index = r3, name = 'O2 q15MinHr2')
avg3PR = Series(index = r3, name = 'PR q15MinHr2')

#average!
for i3 in r3:
    avg3PI[i3] = df3PI[i3:(i3+win3)].mean()
    avg3O2[i3] = df3O2[i3:(i3+win3)].mean()
    avg3PR[i3] = df3PR[i3:(i3+win3)].mean()

result3 = concat([avg3PI, avg3O2, avg3PR], axis=1, join='inner')
print result3


I am working on the file "Old Code/Masimo160127.ipynb".
The first task is:
Average Every Hour 4-24 Hours Post ROP Exam
Can you write Python code for it?

#AVERAGE EVERY 60 MINUTES 4-24 HOURS AFTER ROP EXAM

def perdelta5(start, end, delta):
    r5 = []
    curr = start
    while curr < end:
        r5.append(curr)
        curr += delta
    return r5

# datetime(year, month, day, hour, etc.)

df5PI = df_clean.PI[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))]
df5O2 = df.SpO2[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))]
df5PR = df.PR[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))]
win5 = timedelta(minutes=60) #any unit of time, make the range

r5 = perdelta5((Z+timedelta(hours=3)), (Z+timedelta(hours=24)), win5)

#make the series to store
avg5PI = Series(index = r5, name = 'PI q60MinHr4+')
avg5O2 = Series(index = r5, name = 'O2 q60MinHr4+')
avg5PR = Series(index = r5, name = 'PR q60MinHr4+')

#average!
for i5 in r5:
    avg5PI[i5] = df5PI[i5:(i5+win5)].mean()
    avg5O2[i5] = df5O2[i5:(i5+win5)].mean()
    avg5PR[i5] = df5PR[i5:(i5+win5)].mean()

result5 = concat([avg5PI, avg5O2, avg5PR], axis=1, join='inner')
print result5


I am working on the file "Old Code/Masimo160127.ipynb".
The first task is:
Mild, Moderate, and Severe Desaturation Events
Can you write Python code for it?

df_O2_pre = df[Y:W]

#Find count of these ranges
below = 0 # v <=80
middle = 0 #v >= 81 and v<=84
above = 0 #v >=85 and v<=89
ls = []

b_dict = {}
m_dict = {}
a_dict = {}

for i, v in df_O2_pre['SpO2'].iteritems():

    if v <= 80: #below block

        if not ls:
            ls.append(v)
        else:
            if ls[0] >= 81: #if the range before was not below 80

                if len(ls) >= 5: #if the range was greater than 10 seconds, set to 5 because data points are every 2

                    if ls[0] <= 84: #was it in the middle range?
                        m_dict[middle] = ls
                        middle += 1
                        ls = [v]
                    elif ls[0] >= 85 and ls[0] <=89: #was it in the above range?
                        a_dict[above] = ls
                        above += 1
                        ls = [v]

                else: #old list wasn't long enough to count
                    ls = [v]
            else: #if in the same range
                ls.append(v)

    elif v >= 81 and v<= 84: #middle block

        if not ls:
            ls.append(v)
        else:
            if ls[0] <= 80 or (ls[0]>=85 and ls[0]<= 89): #if not in the middle range
                if len(ls) >= 5: #if range was greater than 10 seconds

                    if ls[0] <= 80: #was it in the below range?
                        b_dict[below] = ls
                        below += 1
                        ls = [v]
                    elif ls[0] >= 85 and ls[0] <=89: #was it in the above range?
                        a_dict[above] = ls
                        above += 1
                        ls = [v]
                else: #old list wasn't long enough to count
                    ls = [v]

            else:
                ls.append(v)

    elif v >= 85 and v <=89: #above block

        if not ls:
            ls.append(v)
        else:
            if ls[0] <=84 : #if not in the above range

                if len(ls) >= 5: #if range was...


I am working on the file "Old Code/Miscellaneous/Masimo Analysis (Old).ipynb".
The first task is:
Average Every 10 Sec During ROP Exam for first 4 minutes
Can you write Python code for it?

#AVERAGE PI DURING ROP EXAM FOR FIRST 4 MINUTES

# Set "X+timedelta(minutes=4)" to "Z" if you want for full duration of exam
def perdelta(start, end, delta):
    r1_PI = []
    curr = start
    while curr < end:
        r1_PI.append(curr)
        curr += delta
    return r1_PI

df1_PI = df_PI[X:X+timedelta(minutes=4)]
win1_PI = timedelta(seconds=10) #any unit of time
#make the range
r1_PI = perdelta(X, X+timedelta(minutes=4), win1_PI)

#make the series to store
avg1_PI = Series(index = r1_PI, name = 'PI During')

#average!
for i1_PI in r1_PI:
    avg1_PI[i1_PI] = df1_PI[i1_PI:(i1_PI+win1_PI)].mean()

#
#AVERAGE SpO2 DURING ROP EXAM
#
def perdelta(start, end, delta):
    r1_O2 = []
    curr = start
    while curr < end:
        r1_O2.append(curr)
        curr += delta
    return r1_O2

df1_O2 = df_O2[X:X+timedelta(minutes=4)]
win1_O2 = timedelta(seconds=10) #any unit of time
#make the range
r1_O2 = perdelta(X, X+timedelta(minutes=4), win1_O2)

#make the series to store
avg1_O2 = Series(index = r1_O2, name = 'SpO2 During')

#average!
for i1_O2 in r1_O2:
    avg1_O2[i1_O2] = df1_O2[i1_O2:(i1_O2+win1_O2)].mean()

#
#AVERAGE PR DURING ROP EXAM
#
def perdelta(start, end, delta):
    r1_PR = []
    curr = start
    while curr < end:
        r1_PR.append(curr)
        curr += delta
    return r1_PR

df1_PR = df_PR[X:X+timedelta(minutes=4)]
win1_PR = timedelta(seconds=10) #any unit of time
#make the range
r1_PR = perdelta(X, X+timedelta(minutes=4), win1_PR)

#make the series to store
avg1_PR = Series(index = r1_PR, name = 'PR During')

#average!
for i1_PR in r1_PR:
    avg1_PR[i1_PR] = df1_PR[i1_PR:(i1_PR+win1_PR)].mean()
avg1_PR

result1 = concat([avg1_PI, avg1_O2, avg1_PR], axis=1, join='inner')
print result1


I am working on the file "Old Code/Miscellaneous/Masimo Analysis (Old).ipynb".
The first task is:
Average Every 15 Min Hours 2-3 Post ROP Exam
Can you write Python code for it?


I am working on the file "Old Code/Miscellaneous/Masimo Analysis (Old).ipynb".
The first task is:
Average Every 30 Min Hours 3-4 Post ROP Exam
Can you write Python code for it?

#
#AVERAGE PI Q 30 MIN HR 3-4 ROP EXAM
#
def perdelta(start, end, delta):
    r4_PI = []
    curr = start
    while curr < end:
        r4_PI.append(curr)
        curr += delta
    return r4_PI

df4_PI = df_PI[(Z+timedelta(hours=2)):(Z+timedelta(hours=3))]
win4_PI = timedelta(minutes=30) #any unit of time
#make the range
r4_PI = perdelta((Z+timedelta(hours=2)), (Z+timedelta(hours=3)), win4_PI)

#make the series to store
avg4_PI = Series(index = r4_PI, name = 'PI q 30min Hr 3-4')

#average!
for i1_PI in r4_PI:
    avg4_PI[i1_PI] = df4_PI[i1_PI:(i1_PI+win4_PI)].mean()

#
#AVERAGE O2 Q 30 MIN HR 3-4 ROP EXAM
#
def perdelta(start, end, delta):
    r4_O2 = []
    curr = start
    while curr < end:
        r4_O2.append(curr)
        curr += delta
    return r4_O2

df4_O2 = df_O2[(Z+timedelta(hours=2)):(Z+timedelta(hours=3))]
win4_O2 = timedelta(minutes=30) #any unit of time
#make the range
r4_O2 = perdelta((Z+timedelta(hours=2)), (Z+timedelta(hours=3)), win4_O2)

#make the series to store
avg4_O2 = Series(index = r4_O2, name = 'O2 q 30min Hr 3-4')

#average!
for i1_O2 in r4_O2:
    avg4_O2[i1_O2] = df4_O2[i1_O2:(i1_O2+win4_O2)].mean()

#
#AVERAGE O2 Q 30 MIN HR 3-4 ROP EXAM
#
def perdelta(start, end, delta):
    r4_O2 = []
    curr = start
    while curr < end:
        r4_O2.append(curr)
        curr += delta
    return r4_O2

df4_O2 = df_O2[(Z+timedelta(hours=2)):(Z+timedelta(hours=3))]
win4_O2 = timedelta(minutes=30) #any unit of time
#make the range
r4_O2 = perdelta((Z+timedelta(hours=2)), (Z+timedelta(hours=3)), win4_O2)

#make the series to store
avg4_O2 = Series(index = r4_O2, name = 'O2 q 30min Hr 3-4')

#average!
for i1_O2 in r4_O2:
    avg4_O2[i1_O2] = df4_O2[i1_O2:(i1_O2+win4_O2)].mean()

#
#AVERAGE PR Q 30 MIN HR 3-4 ROP EXAM
#
def perdelta(start, end, delta):
    r4_PR = []
    curr = start
    while curr < end:
        r4_PR.append(curr)
        curr += delta
    return r4_PR

df4_PR = df_PR[(Z+timedelta(hours=2)):(Z+timedelta(hours=3))]
win4_PR = timedelta(minutes=30) #any unit of time
#make the...


I am working on the file "Old Code/Miscellaneous/Masimo Analysis (Old).ipynb".
The first task is:
Average Every 5 Min Hours 1-2 Post ROP Exam
Can you write Python code for it?

#AVERAGE PI EVERY 5 MIN AFTER HOUR 1 ROP EXAM
def perdelta(start, end, delta):
    r2_PI = []
    curr = start
    while curr < end:
        r2_PI.append(curr)
        curr += delta
    return r2_PI

df2_PI = df_PI[Z:(Z+timedelta(hours=1))]
win2_PI = timedelta(minutes=5) #any unit of time
#make the range
r2_PI = perdelta(Z, (Z+timedelta(hours=1)), win2_PI)

#make the series to store
avg2_PI = Series(index = r2_PI, name = 'PI q 5 Min Hr 1-2')

#average!
for i1_PI in r2_PI:
    avg2_PI[i1_PI] = df2_PI[i1_PI:(i1_PI+win2_PI)].mean()

#
#AVERAGE SpO2 Q 5 MIN HR 1-2 ROP EXAM
#
def perdelta(start, end, delta):
    r2_O2 = []
    curr = start
    while curr < end:
        r2_O2.append(curr)
        curr += delta
    return r2_O2

df2_O2 = df_O2[Z:(Z+timedelta(hours=1))]
win2_O2 = timedelta(minutes=5) #any unit of time
#make the range
r2_O2 = perdelta(Z, (Z+timedelta(hours=1)), win2_O2)

#make the series to store
avg2_O2 = Series(index = r2_O2, name = 'SpO2 q 5 Min Hr 1-2')

#average!
for i1_O2 in r2_O2:
    avg2_O2[i1_O2] = df2_O2[i1_O2:(i1_O2+win2_O2)].mean()

#AVERAGE PR Q 5 MIN HR 1-2 ROP EXAM

def perdelta(start, end, delta):
    r2_PR = []
    curr = start
    while curr < end:
        r2_PR.append(curr)
        curr += delta
    return r2_PR

df2_PR = df_PR[Z:(Z+timedelta(hours=1))]
win2_PR = timedelta(minutes=5) #any unit of time
#make the range
r2_PR = perdelta(Z, (Z+timedelta(hours=1)), win2_PR)

#make the series to store
avg2_PR = Series(index = r2_PR, name = 'PR q 5 Min Hr 1-2')

#average!
for i1_PR in r2_PR:
    avg2_PR[i1_PR] = df2_PR[i1_PR:(i1_PR+win2_PR)].mean()
avg2_PR

result2 = concat([avg2_PI, avg2_O2, avg2_PR], axis=1, join='inner')
print result2


I am working on the file "Old Code/Miscellaneous/Masimo Analysis (Old).ipynb".
The first task is:
Baseline Average
Can you write Python code for it?

df0_PI = df_PI[Y:X]
avg0_PI = df0_PI.mean()

df0_O2 = df_O2[Y:X]
avg0_O2 = df0_O2.mean()

df0_PR = df_PR[Y:X]
avg0_PR = df0_PR.mean()

#df.std() for standard deviation

print ['Baseline Avgs', avg0_PI, avg0_O2, avg0_PR]


I am working on the file "Old Code/Miscellaneous/Masimo Analysis (Old).ipynb".
The first task is:
Export Data out to CSV
Used for fast exporting into Excel and SPSS after tranpose
CHANGE THE FILE NAME!!!!!!!!!!!!!!!!!
Can you write Python code for it?


I am working on the file "Old Code/Miscellaneous/Masimo Analysis (Old).ipynb".
The first task is:
Mild, Moderate, and Severe Desaturation Events
Can you write Python code for it?