In [9]:
%matplotlib inline
In [10]:
from __future__ import division
from numpy.random import randn
import numpy as np
np.set_printoptions(precision=4, suppress=True)
In [11]:
data = randn(2, 3)
In [12]:
data
Out[12]:
In [13]:
data * 10
Out[13]:
In [14]:
data + data
Out[14]:
In [15]:
data.shape
Out[15]:
In [16]:
data.dtype
Out[16]:
In [17]:
data1 = [6, 7.5, 8, 0, 1]
arr1 = np.array(data1)
arr1
Out[17]:
In [18]:
data2 = [[1, 2, 3, 4], [5, 6, 7, 8]]
arr2 = np.array(data2)
arr2
arr2.ndim
arr2.shape
Out[18]:
In [19]:
arr1.dtype
arr2.dtype
Out[19]:
In [20]:
np.zeros(10)
np.zeros((3, 6))
np.empty((2, 3, 2))
Out[20]:
In [21]:
np.arange(15)
Out[21]:
In [22]:
arr1 = np.array([1, 2, 3], dtype=np.float64)
arr2 = np.array([1, 2, 3], dtype=np.int32)
arr1.dtype
arr2.dtype
Out[22]:
In [23]:
arr = np.array([1, 2, 3, 4, 5])
arr.dtype
float_arr = arr.astype(np.float64)
float_arr.dtype
Out[23]:
In [24]:
arr = np.array([3.7, -1.2, -2.6, 0.5, 12.9, 10.1])
arr
arr.astype(np.int32)
Out[24]:
In [25]:
numeric_strings = np.array(['1.25', '-9.6', '42'], dtype=np.string_)
numeric_strings.astype(float)
Out[25]:
In [26]:
int_array = np.arange(10)
calibers = np.array([.22, .270, .357, .380, .44, .50], dtype=np.float64)
int_array.astype(calibers.dtype)
Out[26]:
In [27]:
empty_uint32 = np.empty(8, dtype='u4')
empty_uint32
Out[27]:
In [28]:
arr = np.array([[1., 2., 3.], [4., 5., 6.]])
In [29]:
arr
Out[29]:
In [30]:
arr * arr
Out[30]:
In [31]:
arr - arr
Out[31]:
In [32]:
1 / arr
Out[32]:
In [33]:
arr ** 0.5
Out[33]:
In [34]:
arr = np.arange(10)
arr
arr[5]
arr[5:8]
arr[5:8] = 12
arr
Out[34]:
In [35]:
arr_slice = arr[5:8]
arr_slice[1] = 12345
arr
arr_slice[:] = 64
arr
Out[35]:
In [36]:
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
arr2d[2]
Out[36]:
In [37]:
arr2d[0][2]
arr2d[0, 2]
Out[37]:
In [38]:
arr3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
arr3d
Out[38]:
In [39]:
arr3d[0]
Out[39]:
In [40]:
old_values = arr3d[0].copy()
arr3d[0] = 42
arr3d
arr3d[0] = old_values
arr3d
Out[40]:
In [41]:
arr3d[1, 0]
Out[41]:
In [42]:
arr[1:6]
Out[42]:
In [43]:
arr2d
arr2d[:2]
Out[43]:
In [44]:
arr2d[:2, 1:]
Out[44]:
In [45]:
arr2d[1, :2]
arr2d[2, :1]
Out[45]:
In [46]:
arr2d[:, :1]
Out[46]:
In [47]:
arr2d[:2, 1:] = 0
arr2d
Out[47]:
In [48]:
names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
names
Out[48]:
In [49]:
data = randn(7, 4)
data
Out[49]:
In [50]:
data.shape
Out[50]:
In [51]:
names == 'Bob'
Out[51]:
In [52]:
data[names == 'Bob']
Out[52]:
In [53]:
data[names == 'Bob', 2:]
data[names == 'Bob', 3]
Out[53]:
In [54]:
names != 'Bob'
data[- (names == 'Bob')]
Out[54]:
In [55]:
mask = (names == 'Bob') | (names == 'Will')
mask
data[mask]
Out[55]:
In [56]:
data[data < 0] = 0
data
Out[56]:
In [57]:
data[names != 'Joe'] = 7
data
Out[57]:
In [58]:
arr = np.empty((8, 4))
for i in range(8):
arr[i] = i
arr
Out[58]:
In [59]:
arr[[4, 3, 0, 6]]
Out[59]:
In [60]:
arr[[-3, -5, -7]]
Out[60]:
In [61]:
# more on reshape in Chapter 12
arr = np.arange(32).reshape((8, 4))
arr
arr[[1, 5, 7, 2], [0, 3, 1, 2]]
Out[61]:
In [62]:
arr[[1, 5, 7, 2]][:, [0, 3, 1, 2]]
Out[62]:
In [63]:
arr[np.ix_([1, 5, 7, 2], [0, 3, 1, 2])]
Out[63]:
In [64]:
arr = np.arange(15).reshape((3, 5))
arr
arr.T
Out[64]:
In [65]:
arr = np.random.randn(6, 3)
np.dot(arr.T, arr)
Out[65]:
In [66]:
arr = np.arange(16).reshape((2, 2, 4))
arr
arr.transpose((1, 0, 2))
Out[66]:
In [67]:
arr
arr.swapaxes(1, 2)
Out[67]:
In [68]:
arr = np.arange(10)
np.sqrt(arr)
np.exp(arr)
Out[68]:
In [69]:
x = randn(8)
y = randn(8)
x
y
np.maximum(x, y) # element-wise maximum
Out[69]:
In [ ]:
arr = randn(7) * 5
np.modf(arr)
In [113]:
points = np.arange(-5, 5, 0.01) # 1000 equally spaced points
xs, ys = np.meshgrid(points, points)
ys
Out[113]:
In [114]:
from matplotlib.pyplot import imshow, title
In [115]:
import matplotlib.pyplot as plt
z = np.sqrt(xs ** 2 + ys ** 2)
z
plt.imshow(z, cmap=plt.cm.gray); plt.colorbar()
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")
Out[115]:
In [116]:
plt.draw()
In [120]:
xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
cond = np.array([True, False, True, True, False])
In [121]:
result = [(x if c else y)
for x, y, c in zip(xarr, yarr, cond)]
result
Out[121]:
In [122]:
result = np.where(cond, xarr, yarr)
result
Out[122]:
In [123]:
arr = randn(4, 4)
arr
np.where(arr > 0, 2, -2)
np.where(arr > 0, 2, arr) # set only positive values to 2
Out[123]:
In [ ]:
# Not to be executed
result = []
for i in range(n):
if cond1[i] and cond2[i]:
result.append(0)
elif cond1[i]:
result.append(1)
elif cond2[i]:
result.append(2)
else:
result.append(3)
In [ ]:
# Not to be executed
np.where(cond1 & cond2, 0,
np.where(cond1, 1,
np.where(cond2, 2, 3)))
In [ ]:
# Not to be executed
result = 1 * cond1 + 2 * cond2 + 3 * -(cond1 | cond2)
In [125]:
arr = np.random.randn(5, 4) # normally-distributed data
arr.mean()
np.mean(arr)
arr.sum()
Out[125]:
In [126]:
arr.mean(axis=1)
arr.sum(0)
Out[126]:
In [127]:
arr = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
arr.cumsum(0)
arr.cumprod(1)
Out[127]:
In [128]:
arr = randn(100)
(arr > 0).sum() # Number of positive values
Out[128]:
In [129]:
bools = np.array([False, False, True, False])
bools.any()
bools.all()
Out[129]:
In [130]:
arr = randn(8)
arr
Out[130]:
In [131]:
arr.sort()
arr
Out[131]:
In [132]:
arr = randn(5, 3)
arr
Out[132]:
In [133]:
arr.sort(1)
arr
Out[133]:
In [ ]:
large_arr = randn(1000)
large_arr.sort()
large_arr[int(0.05 * len(large_arr))] # 5% quantile
In [ ]:
names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
np.unique(names)
ints = np.array([3, 3, 3, 2, 2, 1, 1, 4, 4])
np.unique(ints)
In [ ]:
sorted(set(names))
In [ ]:
values = np.array([6, 0, 0, 3, 2, 5, 6])
np.in1d(values, [2, 3, 6])
In [ ]:
arr = np.arange(10)
np.save('some_array', arr)
In [ ]:
np.load('some_array.npy')
In [ ]:
np.savez('array_archive.npz', a=arr, b=arr)
In [ ]:
arch = np.load('array_archive.npz')
arch['b']
In [ ]:
!rm some_array.npy
!rm array_archive.npz
In [ ]:
!cat array_ex.txt
In [ ]:
arr = np.loadtxt('array_ex.txt', delimiter=',')
arr
In [ ]:
x = np.array([[1., 2., 3.], [4., 5., 6.]])
y = np.array([[6., 23.], [-1, 7], [8, 9]])
x
y
x.dot(y) # equivalently np.dot(x, y)
In [ ]:
np.dot(x, np.ones(3))
In [ ]:
np.random.seed(12345)
In [ ]:
from numpy.linalg import inv, qr
X = randn(5, 5)
mat = X.T.dot(X)
inv(mat)
mat.dot(inv(mat))
q, r = qr(mat)
r
In [ ]:
samples = np.random.normal(size=(4, 4))
samples
In [ ]:
from random import normalvariate
N = 1000000
%timeit samples = [normalvariate(0, 1) for _ in xrange(N)]
%timeit np.random.normal(size=N)
In [ ]:
np.random.seed(12345)
In [ ]:
nsteps = 1000
draws = np.random.randint(0, 2, size=nsteps)
steps = np.where(draws > 0, 1, -1)
walk = steps.cumsum()
In [ ]:
walk.min()
walk.max()
In [ ]:
(np.abs(walk) >= 10).argmax()
In [ ]:
nwalks = 5000
nsteps = 1000
draws = np.random.randint(0, 2, size=(nwalks, nsteps)) # 0 or 1
steps = np.where(draws > 0, 1, -1)
walks = steps.cumsum(1)
walks
In [ ]:
walks.max()
walks.min()
In [ ]:
hits30 = (np.abs(walks) >= 30).any(1)
hits30
hits30.sum() # Number that hit 30 or -30
In [ ]:
crossing_times = (np.abs(walks[hits30]) >= 30).argmax(1)
crossing_times.mean()
In [ ]:
steps = np.random.normal(loc=0, scale=0.25,
size=(nwalks, nsteps))
In [ ]: