In [1]:
%matplotlib inline
import numpy as np
In [19]:
arr = np.array([[1,2,3],[4,5,6]], dtype=np.float64)
In [28]:
arr
Out[28]:
In [23]:
arr*arr
Out[23]:
In [24]:
np.dot(arr.T,arr)
Out[24]:
In [25]:
np.dot(arr,arr.T)
Out[25]:
In [26]:
arr+5
Out[26]:
In [31]:
arr+np.array([[6],[7]]) # Broadcast along dim 1
Out[31]:
In [32]:
arr+np.array([6,7,8]) # Breadcast along dim 0
Out[32]:
In [49]:
# Slicing - always returns a view
arr[:,1:]
Out[49]:
In [34]:
# Boolean indexing - always creates a copy
names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
data = np.random.randn(names.shape[0],4)
In [35]:
data
Out[35]:
In [36]:
names
Out[36]:
In [38]:
data[names=='Bob', :2]
Out[38]:
In [46]:
data[[4,2],[1,2]] # Fancy indexing - extract the specified elements
Out[46]:
In [47]:
data[np.ix_([4,2], [1,2])] # Get the square region
Out[47]:
In [50]:
# Vectorization
points = np.arange(-5,5,0.01)
xs, ys = np.meshgrid(points, points)
In [51]:
import matplotlib.pyplot as plt
In [52]:
z = np.sqrt( xs**2 + ys**2 )
In [112]:
# Alternative: no need for intermediate 2D arrays if use broadcasting
z2 = np.sqrt(points**2 + points[:,None]**2)
In [108]:
np.arange(4)+np.arange(4)[:,None]
Out[108]:
In [109]:
points.shape
Out[109]:
In [110]:
points.T.shape
Out[110]:
In [111]:
points[:,None].shape #Convert to column vector
Out[111]:
In [120]:
points[None,:].T.shape
Out[120]:
In [118]:
plt.imshow(z2, cmap=plt.cm.gray); plt.colorbar
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")
Out[118]:
In [89]:
# Random walk - NB: using
x = np.hstack((np.zeros((10,1)), np.random.normal(loc=0, scale=0.25, size=(10,100)).cumsum(1))).T
plt.plot(x)
Out[89]:
In [92]:
x[:10,:5]
Out[92]:
In [ ]: