In [ ]:
from __future__ import absolute_import, division, print_function

Further Python Basics


In [ ]:
names = ['alice', 'jonathan', 'bobby']
ages = [24, 32, 45]
ranks = ['kinda cool', 'really cool', 'insanely cool']

In [ ]:
for (name, age, rank) in zip(names, ages, ranks):
    print(name, age, rank)

In [ ]:
for index, (name, age, rank) in enumerate(zip(names, ages, ranks)):
    print(index, name, age, rank)

In [ ]:
# return, esc, shift+enter, ctrl+enter
# text keyboard shortcuts -- cmd > (right), < left,
# option delete (deletes words)
# type "h" for help
# tab
# shift-tab
# keyboard shortcuts
#  - a, b, y, m, dd, h, ctrl+shift+-

In [ ]:
%matplotlib inline
%config InlineBackend.figure_format='retina'

import matplotlib.pyplot as plt
# no pylab
import seaborn as sns
sns.set_context('talk')
sns.set_style('darkgrid') 
plt.rcParams['figure.figsize'] = 12, 8  # plotsize 

import numpy as np
# don't do `from numpy import *`
import pandas as pd

In [ ]:
# If you have a specific function that you'd like to import
from numpy.random import randn

In [ ]:
x = np.arange(100)
y = np.sin(x)
plt.plot(x, y);

In [ ]:
%matplotlib notebook

In [ ]:
x = np.arange(10)
y = np.sin(x)
plt.plot(x, y)#;

Magics!

  • % and %% magics
  • interact
  • embed image
  • embed links, youtube
  • link notebooks

Check out http://matplotlib.org/gallery.html select your favorite.


In [ ]:
%%bash
for num in {1..5}
do
    for infile in *;
    do
        echo $num $infile
    done
    wc $infile
done

In [ ]:
print("hi")
!pwd

In [ ]:
!ping google.com

In [ ]:
this_is_magic = "Can you believe you can pass variables and strings like this?"

In [ ]:
!echo $this_is_magic

In [ ]:
hey

Numpy

If you have arrays of numbers, use numpy or pandas (built on numpy) to represent the data. Tons of very fast underlying code.


In [ ]:
x = np.arange(10000)

print(x)  # smart printing

In [ ]:
print(x[0]) # first element 
print(x[-1]) # last element
print(x[0:5]) # first 5 elements (also x[:5])
print(x[:]) # "Everything"

In [ ]:
print(x[-5:]) # last five elements

In [ ]:
print(x[-5:-2])

In [ ]:
print(x[-5:-1]) # not final value -- not inclusive on right

In [ ]:


In [ ]:
x = np.random.randint(5, 5000, (3, 5))

In [ ]:
x

In [ ]:
np.sum(x)

In [ ]:
x.sum()

In [ ]:
np.sum(x)

In [ ]:
np.sum(x, axis=0)

In [ ]:
np.sum(x, axis=1)

In [ ]:
x.sum(axis=1)

In [ ]:
# Multi dimension array slice with a comma
x[:, 2]

In [ ]:


In [ ]:
y = np.linspace(10, 20, 11)
y

In [ ]:
np.linspace?

In [ ]:
np.linspace()
# shift-tab; shift-tab-tab
np.

In [ ]:
def does_it(first=x, second=y):
    """This is my doc"""
    pass

In [ ]:
y[[3, 5, 7]]

In [ ]:
does_it()

In [ ]:
num = 3000
x = np.linspace(1.0, 300.0, num)
y = np.random.rand(num)
z = np.sin(x)
np.savetxt("example.txt", np.transpose((x, y, z)))

In [ ]:
%less example.txt

In [ ]:
!wc example.txt

In [ ]:
!head example.txt

In [ ]:
#Not a good idea
a = []
b = []
for line in open("example.txt", 'r'):
    a.append(line[0])
    b.append(line[2])
    
a[:10] # Whoops!

In [ ]:
a = []
b = []
for line in open("example.txt", 'r'):
    line = line.split()
    a.append(line[0])
    b.append(line[2])
    
a[:10] # Strings!

In [ ]:
a = []
b = []
for line in open("example.txt", 'r'):
    line = line.split()
    a.append(float(line[0]))
    b.append(float(line[2]))
    
a[:10] # Lists!

In [ ]:
# Do this!
a, b = np.loadtxt("example.txt", unpack=True, usecols=(0,2))

In [ ]:
a

Matplotlib and Numpy


In [ ]:
from numpy.random import randn

In [ ]:
num = 50
x = np.linspace(2.5, 300, num)
y = randn(num)
plt.scatter(x, y)

In [ ]:
y > 1

In [ ]:
y[y > 1]

In [ ]:
y[(y < 1) & (y > -1)]

In [ ]:
plt.scatter(x, y, c='b', s=50)
plt.scatter(x[(y < 1) & (y > -1)], y[(y < 1) & (y > -1)], c='r', s=50)

In [ ]:
y[~((y < 1) & (y > -1))] = 1.0
plt.scatter(x, y, c='b')
plt.scatter(x, np.clip(y, -0.5, 0.5), color='red')

In [ ]:
num = 350
slope = 0.3
x = randn(num) * 50. + 150.0 
y = randn(num) * 5 + x * slope
plt.scatter(x, y, c='b')

In [ ]:
# plt.scatter(x[(y < 1) & (y > -1)], y[(y < 1) & (y > -1)], c='r')
# np.argsort, np.sort, complicated index slicing
dframe = pd.DataFrame({'x': x, 'y': y})
g = sns.jointplot('x', 'y', data=dframe, kind="reg")

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]: