Getting On with Numpy

import numpy as np

Numpy ndarrays and regular lists

a = range(5)
b = [0,1,2,3,4]
print 'a is {} and b is {}'.format(a,b)
c = np.arange(5)
d = np.array([0,1,2,3,4])
print 'c is {} and d is {}'.format(c, d)
print a+b
print c+d

What is broadcasting and why does it matter?

let’s say that we want b to follow a, we just need to add 5 to each element of b

b = [i+5 for i in b]
print 'this is a slow b', a+b

with numpy it’s one operation

d+=5
print 'this is a fast d', np.append(c,d)

this also works with multiplication and division

c * 20
d/-2

aaah what happened there? truncation?

dtype

a = np.arange(5)
print a.dtype
b = np.arange(5, dtype='float64')
print b.dtype
print (a*b).dtype

available types are:

converting lists to arrays

a = range(5)
b = np.asarray(a)
c = np.array(a)
print "a, b and c are", a, b, c

Multiple dimensions

d = np.array([a,b,c])
e = np.vstack([a,b,c])
f = np.hstack([a,b,c])
print "d is", d
print "e is", e
print "f is", f

hstack seen here is roughly equivalent to np.append seen before and also np.concatenate if you’re more into c style

back to edition