In [1]:
import numpy, scipy, matplotlib.pyplot as plt, pandas, librosa

NumPy, SciPy, and Matplotlib

Special Arrays

In [2]:
print numpy.arange(5)
[0 1 2 3 4]
In [3]:
print numpy.linspace(0, 5, 10, endpoint=False)
[ 0.   0.5  1.   1.5  2.   2.5  3.   3.5  4.   4.5]
In [4]:
print numpy.zeros(5)
[ 0.  0.  0.  0.  0.]
In [5]:
print numpy.ones(5)
[ 1.  1.  1.  1.  1.]
In [6]:
print numpy.ones((5,2))
[[ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]]
In [7]:
print scipy.randn(5) # random Gaussian, zero-mean unit-variance
[-1.54495129  1.43194246  0.84831827  1.53272595 -0.82275569]
In [8]:
print scipy.randn(5,2)
[[ 0.99898659  0.48738883]
 [ 0.19482165 -1.04052195]
 [-1.52284225 -0.27679628]
 [ 1.39272206 -1.16680744]
 [ 1.45907927  1.62887006]]

Slicing Arrays

In [9]:
x = numpy.arange(10)
print x[2:4]
[2 3]
In [10]:
print x[-1]
9
In [11]:
print x[0:8:2]
[0 2 4 6]
In [12]:
print x[4:2:-1]
[4 3]
In [13]:
print x[:4]
[0 1 2 3]
In [14]:
print x[:999]
[0 1 2 3 4 5 6 7 8 9]
In [15]:
print x[::-1]
[9 8 7 6 5 4 3 2 1 0]

Array Arithmetic

In [16]:
x = numpy.arange(5)
y = numpy.ones(5)
print x+2*y
[ 2.  3.  4.  5.  6.]
In [17]:
x = scipy.randn(5)
y = numpy.ones(5)
print numpy.dot(x, y)
0.841960712473
In [18]:
x = scipy.randn(5,3)
y = numpy.ones((3,2))
print numpy.dot(x, y)
[[-0.99186397 -0.99186397]
 [-2.11558878 -2.11558878]
 [ 0.30387018  0.30387018]
 [ 0.40770085  0.40770085]
 [ 0.52671539  0.52671539]]

Boolean Operations

In [19]:
x = numpy.arange(10)
print x < 5
[ True  True  True  True  True False False False False False]
In [20]:
y = numpy.ones(10)
print x < y
[ True False False False False False False False False False]

Distance Metrics

In [21]:
from scipy.spatial import distance
print distance.euclidean([0, 0], [3, 4])
print distance.sqeuclidean([0, 0], [3, 4])
print distance.cityblock([0, 0], [3, 4])
print distance.chebyshev([0, 0], [3, 4])
5.0
25.0
7
4
In [22]:
print distance.cosine([67, 0], [89, 0])
print distance.cosine([67, 0], [0, 89])
0.0
1.0

Sorting

In [23]:
x = scipy.randn(5)
print x
x.sort()
print x
[-1.99963778 -0.81914671  0.54726579  0.14279565  0.43234242]
[-1.99963778 -0.81914671  0.14279565  0.43234242  0.54726579]
In [24]:
x = scipy.randn(5)
print x
ind = numpy.argsort(x)
print ind
print x[ind]
[ 0.17615195  0.45468544  0.07219588 -0.89896614 -0.34038053]
[3 4 2 0 1]
[-0.89896614 -0.34038053  0.07219588  0.17615195  0.45468544]