In [2]:
import numpy as np
a = np.array([1,2,3,4])
print(a)


[1 2 3 4]

In [11]:
import time

a = np.random.rand(1000000)
b = np.random.rand(1000000)

tic = time.time()
c = np.dot(a,b)
toc = time.time()
print("Vectorized version: " + str(1000*(toc-tic)) + " ms")

c = 0
tic = time.time()
for i in range(1000000):
    c += a[i]*b[i]
toc = time.time()
print("For loop version: " + str(1000*(toc-tic)) + " ms")


Vectorized version: 1.1131763458251953 ms
For loop version: 456.8037986755371 ms

In [12]:
A = np.array([[56.0, 0.0, 4.4, 68.0],
              [1.2, 104.0, 52.0, 8.0],
              [1.8, 135.0, 99.0, 0.9]])
print(A)


[[  56.     0.     4.4   68. ]
 [   1.2  104.    53.     8. ]
 [   1.8  135.    99.     0.9]]

In [13]:
cal = A.sum(axis = 0)
print(cal)


[  59.   239.   156.4   76.9]

In [14]:
percentage = 100*A/cal.reshape(1,4)
print(percentage)


[[ 94.91525424   0.           2.81329923  88.42652796]
 [  2.03389831  43.51464435  33.88746803  10.40312094]
 [  3.05084746  56.48535565  63.29923274   1.17035111]]

In [26]:
a = np.random.randn(5,1)
print(a)


[[ 0.80643159]
 [ 0.16739576]
 [-0.64283226]
 [-0.71635633]
 [-0.78895899]]

In [27]:
print(a.shape)


(5, 1)

In [28]:
print(a.T)


[[ 0.80643159  0.16739576 -0.64283226 -0.71635633 -0.78895899]]

In [31]:
print(np.dot(a,a.T))


[[ 0.65033191  0.13499323 -0.51840025 -0.57769238 -0.63624145]
 [ 0.13499323  0.02802134 -0.1076074  -0.11991501 -0.13206839]
 [-0.51840025 -0.1076074   0.41323332  0.46049696  0.50716829]
 [-0.57769238 -0.11991501  0.46049696  0.51316639  0.56517577]
 [-0.63624145 -0.13206839  0.50716829  0.56517577  0.62245629]]

In [63]:
a = np.random.randn(3,4)
b = np.random.randn(4,1)
c = np.zeros([3,4])
# for loop
for i in range(3):
  for j in range(4):
    c[i][j] = a[i][j] + b[j]
print(c)

# vectorization
c = np.zeros([3,4])
c = a + b.T
print(c)


[[ 1.89047446  1.81516654 -0.55663873  0.40002315]
 [-1.00239767  0.37057919 -0.78413048  0.38743639]
 [ 0.14915671 -0.11771435 -3.50683681  2.27243449]]
[[ 1.89047446  1.81516654 -0.55663873  0.40002315]
 [-1.00239767  0.37057919 -0.78413048  0.38743639]
 [ 0.14915671 -0.11771435 -3.50683681  2.27243449]]

In [ ]:
a = np.random.randn(3, 3)
b = np.random.randn(3, 1)
c = a*b