# In[1]
a=np.array([0,1,2])
M=np.ones((3,3))
M+a
# Out[1]
array([[1., 2., 3.],
[1., 2., 3.],
[1., 2., 3.]])
a
is stretched(broadcasted), across the second dimension in order to match the shape of M
.# In[2]
a=np.arange(3)
b=np.arange(3)[:,np.newaxis]
print(a)
print(b)
print(a+b)
# Out[2]
[0 1 2]
[[0]
[1]
[2]]
[[0 1 2]
[1 2 3]
[2 3 4]]
a
and b
both stretched or broadcasted to match a common shape, and the result is a two-dimensional array.# In[3]
M=np.ones((2,3))
a=np.arange(3)
M.shape
is (2,3) , and a.shape
is (3,)a
has fewer dimensions, so we pad it on the left with ones.M.shape
remains (2,3), a.shape
becomes (1,3)M.shape
remains (2,3), a.shape
becomes (2,3)# In[4]
M+a
# Out[4]
array([[1.,2.,3.],
[1.,2.,3.]])
# In[5]
a=np.arange(3).reshape((3,1))
b=np.arange(3)
a.shape
is (3,1), and b.shape
is (3,)a.shape
remains (3,1), and b.shape
becomes (1,3)a.shape
becomes (3,3), and b.shape
becomes (3,3)# In[6]
a+b
# Out[6]
array([[0,1,2],
[1,2,3],
[2,3,4]])
# In[7]
M=np.ones((3,2))
a=np.arange(3)
M.shape
is (3,2), and a.shape
is (3,)M.shape
remains (3,2), and a.shape
becomes (1,3)M.shape
remains (3,2), and a.shape
becomes (3,3)# In[8]
X=np.random.random((10,3))
print(X)
# Out[8]
[[0.79578526 0.06970127 0.80572102]
[0.49596132 0.4203202 0.46907811]
[0.14083824 0.66032281 0.86455548]
[0.06037715 0.83184264 0.54172137]
[0.38316786 0.05267514 0.70413834]
[0.05020395 0.78665839 0.7274787 ]
[0.47849237 0.98020416 0.44380548]
[0.58073628 0.97996138 0.40468001]
[0.25097966 0.39015983 0.79417086]
[0.39169738 0.96715734 0.56671287]]
# In[9]
Xmean=X.mean(0) # X.mean('axis')
Xmean
# Out[9]
array([0.36282395, 0.61390031, 0.63220622])
X
array by subtracting the mean# In[10]
X_centered=X-Xmean
X_centered.mean(0)
# Out[10]
array([ 6.66133815e-17, -4.44089210e-17, -6.66133815e-17])
# In[11]
x=np.linspace(0,5,50)
y=np.linspace(0,5,50)[:,np.newaxis]
z=np.sin(x)**10+np.cos(10+y*x)*np.cos(x)
# In[12]
%matplotlib inline
import matplotlib.pyplot as plt
plt.imshow(z,origin='lower',extent=[0,5,0,5],cmap='viridis')
plt.colorbar();
References:
1) https://jakevdp.github.io/PythonDataScienceHandbook/02.05-computation-on-arrays-broadcasting.html