Numpy and R

(inspired from 100 numpy exercises)

  • Create vectors of zeros of size 10
In [27]:
import numpy as np
np.zeros(10)
Out[27]:
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

Create a vector with values ranging from 10 to 49

In [26]:
np.arange(10,50)
Out[26]:
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
       27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
       44, 45, 46, 47, 48, 49])
  • Reverse a vector
In [69]:
v = np.array([1,10,20,30])
v[::-1]
Out[69]:
array([30, 20, 10,  1])
  • Create a 4x3 matrix with values ranging from 0 to 11
In [71]:
z=np.arange(12)
print(z.reshape(4,3))
print("----")
print(z.reshape(4,3).transpose())
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
----
[[ 0  3  6  9]
 [ 1  4  7 10]
 [ 2  5  8 11]]
  • Find indices of non-zero elements from [1,2,0,0,4,0]
In [74]:
z=np.array([1,2,0,0,4,0])
np.where(z==0)
Out[74]:
(array([2, 3, 5], dtype=int64),)
  • Create a 3x3 identity matrix
In [44]:
np.eye(3)
Out[44]:
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
  • Create a 3x3x3 array with random values
In [149]:
np.random.seed(9999999) # ransom output will be same
np.random.random((3,3,3))
Out[149]:
array([[[ 0.81941195,  0.00892889,  0.37775741],
        [ 0.45132896,  0.18317238,  0.42277954],
        [ 0.30486314,  0.23538705,  0.72474768]],

       [[ 0.53814568,  0.90348328,  0.11052117],
        [ 0.76930135,  0.16841091,  0.83273551],
        [ 0.75869139,  0.64357612,  0.86298884]],

       [[ 0.54983413,  0.24602741,  0.52455066],
        [ 0.80711061,  0.41454819,  0.42564701],
        [ 0.30793544,  0.38907987,  0.33766743]]])
  • Create a 10x10 array with random values and find the minimum and maximum values
In [116]:
np.random.seed(2399999) # ransom output will be same
Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)
0.000224452747766 0.978303360153
  • Create a random vector of size 30 and find the mean value
In [135]:
np.random.seed(13999)
#np.random.random(30).mean()
#or
np.mean(np.random.random(30))
Out[135]:
0.45940901080110719
  • Create a 2d array with 1 on the border and 0 inside
In [148]:
z=np.ones((10,10))
z[1:-1,1:-1]=0
z
Out[148]:
array([[ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]])
  • file details "C:\Users\mahes\100 exercises in Python.ipynb"
In [ ]:
 
In [ ]:
 
In [ ]: