NumPy Library


NumPY
In [4]:
#basic numpy option

import numpy as np

a = np.arange(15).reshape(3, 5)

a

a.shape

a.ndim

a.dtype.name

a.itemsize

a.size

type(a)


b = np.array([6, 7, 8])

type (b)


a = np.array([2,3,4])

a.dtype

b = np.array([1.2, 3.5, 5.1])

b.dtype


b = np.array([(1.5,2,3), (4,5,6),(4,6,7)])

c = np.array ( [ [1,2], [3,4] ], dtype=complex )

print (c)

np.zeros( (3,4) )

np.ones( (2,3,4), dtype=np.int16 )

print (np.empty( (2,3) ))

print (np.arange(10,30,5))

print (np.arange(1.2,3,0.2))
[[ 1.+0.j  2.+0.j]
 [ 3.+0.j  4.+0.j]]
[[  1.39069238e-309   1.39069238e-309   1.39069238e-309]
 [  1.39069238e-309   1.39069238e-309   1.39069238e-309]]
[10 15 20 25]
[ 1.2  1.4  1.6  1.8  2.   2.2  2.4  2.6  2.8]
In [7]:
from numpy import pi
np.linspace(0,2,10) # 10 numbers from 0 to 2
Out[7]:
array([ 0.        ,  0.22222222,  0.44444444,  0.66666667,  0.88888889,
        1.11111111,  1.33333333,  1.55555556,  1.77777778,  2.        ])
In [13]:
x = np.linspace( 0, 2*pi, 100 )
print (x)

f = np.sin(x)
print (f)
[ 0.          0.06346652  0.12693304  0.19039955  0.25386607  0.31733259
  0.38079911  0.44426563  0.50773215  0.57119866  0.63466518  0.6981317
  0.76159822  0.82506474  0.88853126  0.95199777  1.01546429  1.07893081
  1.14239733  1.20586385  1.26933037  1.33279688  1.3962634   1.45972992
  1.52319644  1.58666296  1.65012947  1.71359599  1.77706251  1.84052903
  1.90399555  1.96746207  2.03092858  2.0943951   2.15786162  2.22132814
  2.28479466  2.34826118  2.41172769  2.47519421  2.53866073  2.60212725
  2.66559377  2.72906028  2.7925268   2.85599332  2.91945984  2.98292636
  3.04639288  3.10985939  3.17332591  3.23679243  3.30025895  3.36372547
  3.42719199  3.4906585   3.55412502  3.61759154  3.68105806  3.74452458
  3.8079911   3.87145761  3.93492413  3.99839065  4.06185717  4.12532369
  4.1887902   4.25225672  4.31572324  4.37918976  4.44265628  4.5061228
  4.56958931  4.63305583  4.69652235  4.75998887  4.82345539  4.88692191
  4.95038842  5.01385494  5.07732146  5.14078798  5.2042545   5.26772102
  5.33118753  5.39465405  5.45812057  5.52158709  5.58505361  5.64852012
  5.71198664  5.77545316  5.83891968  5.9023862   5.96585272  6.02931923
  6.09278575  6.15625227  6.21971879  6.28318531]
[  0.00000000e+00   6.34239197e-02   1.26592454e-01   1.89251244e-01
   2.51147987e-01   3.12033446e-01   3.71662456e-01   4.29794912e-01
   4.86196736e-01   5.40640817e-01   5.92907929e-01   6.42787610e-01
   6.90079011e-01   7.34591709e-01   7.76146464e-01   8.14575952e-01
   8.49725430e-01   8.81453363e-01   9.09631995e-01   9.34147860e-01
   9.54902241e-01   9.71811568e-01   9.84807753e-01   9.93838464e-01
   9.98867339e-01   9.99874128e-01   9.96854776e-01   9.89821442e-01
   9.78802446e-01   9.63842159e-01   9.45000819e-01   9.22354294e-01
   8.95993774e-01   8.66025404e-01   8.32569855e-01   7.95761841e-01
   7.55749574e-01   7.12694171e-01   6.66769001e-01   6.18158986e-01
   5.67059864e-01   5.13677392e-01   4.58226522e-01   4.00930535e-01
   3.42020143e-01   2.81732557e-01   2.20310533e-01   1.58001396e-01
   9.50560433e-02   3.17279335e-02  -3.17279335e-02  -9.50560433e-02
  -1.58001396e-01  -2.20310533e-01  -2.81732557e-01  -3.42020143e-01
  -4.00930535e-01  -4.58226522e-01  -5.13677392e-01  -5.67059864e-01
  -6.18158986e-01  -6.66769001e-01  -7.12694171e-01  -7.55749574e-01
  -7.95761841e-01  -8.32569855e-01  -8.66025404e-01  -8.95993774e-01
  -9.22354294e-01  -9.45000819e-01  -9.63842159e-01  -9.78802446e-01
  -9.89821442e-01  -9.96854776e-01  -9.99874128e-01  -9.98867339e-01
  -9.93838464e-01  -9.84807753e-01  -9.71811568e-01  -9.54902241e-01
  -9.34147860e-01  -9.09631995e-01  -8.81453363e-01  -8.49725430e-01
  -8.14575952e-01  -7.76146464e-01  -7.34591709e-01  -6.90079011e-01
  -6.42787610e-01  -5.92907929e-01  -5.40640817e-01  -4.86196736e-01
  -4.29794912e-01  -3.71662456e-01  -3.12033446e-01  -2.51147987e-01
  -1.89251244e-01  -1.26592454e-01  -6.34239197e-02  -2.44929360e-16]
In [21]:
a = np.arange(6)
print (a)

b = np.arange(12).reshape(3,4) 
print (b)


c= np.arange(24).reshape(2,4,3)
print("\n", c)
[0 1 2 3 4 5]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

 [[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]
  [ 9 10 11]]

 [[12 13 14]
  [15 16 17]
  [18 19 20]
  [21 22 23]]]
In [22]:
print(np.arange(10000))
[   0    1    2 ..., 9997 9998 9999]
In [25]:
print (np.arange(10000).reshape(100,100))
[[   0    1    2 ...,   97   98   99]
 [ 100  101  102 ...,  197  198  199]
 [ 200  201  202 ...,  297  298  299]
 ..., 
 [9700 9701 9702 ..., 9797 9798 9799]
 [9800 9801 9802 ..., 9897 9898 9899]
 [9900 9901 9902 ..., 9997 9998 9999]]
In [26]:
np.set_printoptions(thresold='nan')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-b91b34b42917> in <module>()
----> 1 np.set_printoptions(thresold='nan')

TypeError: set_printoptions() got an unexpected keyword argument 'thresold'
In [32]:
a= np.array([21,30,40,50])
b= np.arange(4)

print ("\n", a)


c=a-b

print ("\n",c)

print ("\n",b**2)

10*np.sin(a)

print ("\n",a<35)
Out[32]:
array([ True,  True, False, False], dtype=bool)
In [39]:
A = np.array([[1,2],
            [3,4]]) 

B = np.array([[5,6],
             [7,8]])
print (A*B)

print ("\n",A.dot(B))

print ("\n", np.dot(A,B))
[[ 5 12]
 [21 32]]

 [[19 22]
 [43 50]]

 [[19 22]
 [43 50]]
In [3]:
a = np.ones((2,3), dtype = int)
print (a)
b = np.random.random((2,3))
print ("\n",b)

a*=3

print (a)

b+=a

print (b)

a += b
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-7d5670a49c18> in <module>()
----> 1 a = np.ones((2,3), dtype = int)
      2 print (a)
      3 b = np.random.random((2,3))
      4 print ("\n",b)
      5 

NameError: name 'np' is not defined
In [12]:
a = np.ones(3, dtype=np.int32)
print (a)

b = np.linspace(0,pi,3)
print (b)
b.dtype.name

c=a+b

print (c)

d = np.exp(c*1j)

print (d)

d.dtype.name
[1 1 1]
[ 0.          1.57079633  3.14159265]
[ 1.          2.57079633  4.14159265]
[ 0.54030231+0.84147098j -0.84147098+0.54030231j -0.54030231-0.84147098j]
Out[12]:
'complex128'
In [19]:
a=np.random.random((2,3))

print (a)

print (a.sum())
print (a.min())
print (a.max())
[[ 0.67068693  0.15791483  0.60558201]
 [ 0.37767671  0.65926175  0.48666188]]
2.95778409983
0.157914825378
0.670686927453
In [24]:
b = np.arange(12).reshape(3,4)

print (b)

print ("\n",b.sum(axis=0))      # sum of each row

print ("\n",b.min(axis=1))      # min of each row

print ("\n",b.cumsum(axis=1))   #cumulative sum along each row
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

 [12 15 18 21]

 [0 4 8]

 [[ 0  1  3  6]
 [ 4  9 15 22]
 [ 8 17 27 38]]
In [28]:
B = np.arange (3)

print (B)

print (np.exp(B))

print (np.sqrt(B))

C = np.array ([2.,-1.,4.])

print (np.add(B,C))
[0 1 2]
[ 1.          2.71828183  7.3890561 ]
[ 0.          1.          1.41421356]
[ 2.  0.  6.]
In [42]:
a= np.arange(10)**3

print (a)

print (a[2])

print (a[2:5])


a[:6:2]=-1000 # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
print (a)

b = a[ : :-1]
print (b)

for i in a:
    print (i**(1/3.))
[  0   1   8  27  64 125 216 343 512 729]
8
[ 8 27 64]
[-1000     1 -1000    27 -1000   125   216   343   512   729]
[  729   512   343   216   125 -1000    27 -1000     1 -1000]
nan
1.0
nan
3.0
nan
5.0
6.0
7.0
8.0
9.0
C:\Users\Sohamc10\Anaconda3\lib\site-packages\ipykernel_launcher.py:17: RuntimeWarning: invalid value encountered in power
In [52]:
def f(x,y):
    return 10*x+y

b = np.fromfunction(f,(5,4), dtype = int)

print (b) 

print (b[2,3])

print (b[0:5, 0])

print (b[-2])
[[ 0  1  2  3]
 [10 11 12 13]
 [20 21 22 23]
 [30 31 32 33]
 [40 41 42 43]]
23
[ 0 10 20 30 40]
[30 31 32 33]
In [63]:
c = np.array([[[0,1,2],
             [10,12,13]],
              [[100,101,102],
              [110,112,113]]])

print (c.shape)

print (c[0,...])

print (c[1])

print (c[...,1])
(2, 2, 3)
[[ 0  1  2]
 [10 12 13]]
[[100 101 102]
 [110 112 113]]
[[  1  12]
 [101 112]]
In [64]:
for row in b:
    print (row)
[0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]
In [66]:
for element in b.flat:
    print (element)
0
1
2
3
10
11
12
13
20
21
22
23
30
31
32
33
40
41
42
43
In [70]:
a = np.floor(10*np.random.random((3,4)))

print (a)

a.shape
[[ 6.  7.  7.  4.]
 [ 9.  9.  3.  8.]
 [ 0.  0.  6.  3.]]
Out[70]:
(3, 4)
In [71]:
a.ravel()  # returns the array, flattened
Out[71]:
array([ 6.,  7.,  7.,  4.,  9.,  9.,  3.,  8.,  0.,  0.,  6.,  3.])
In [72]:
a.reshape (6,2)
Out[72]:
array([[ 6.,  7.],
       [ 7.,  4.],
       [ 9.,  9.],
       [ 3.,  8.],
       [ 0.,  0.],
       [ 6.,  3.]])
In [73]:
a.T
Out[73]:
array([[ 6.,  9.,  0.],
       [ 7.,  9.,  0.],
       [ 7.,  3.,  6.],
       [ 4.,  8.,  3.]])
In [74]:
a.T.shape
Out[74]:
(4, 3)
In [75]:
a.shape
Out[75]:
(3, 4)
In [76]:
a
Out[76]:
array([[ 6.,  7.,  7.,  4.],
       [ 9.,  9.,  3.,  8.],
       [ 0.,  0.,  6.,  3.]])
In [78]:
a.resize((2,6))
a
Out[78]:
array([[ 6.,  7.,  7.,  4.,  9.,  9.],
       [ 3.,  8.,  0.,  0.,  6.,  3.]])
In [79]:
a.reshape(3,-1)
Out[79]:
array([[ 6.,  7.,  7.,  4.],
       [ 9.,  9.,  3.,  8.],
       [ 0.,  0.,  6.,  3.]])
In [80]:
a = np.floor(10*np.random.random((2,2)))
a
Out[80]:
array([[ 7.,  2.],
       [ 8.,  8.]])
In [82]:
b = np.floor(10*np.random.random((2,2)))

b
Out[82]:
array([[ 9.,  5.],
       [ 4.,  3.]])
In [83]:
np.vstack ((a,b))
Out[83]:
array([[ 7.,  2.],
       [ 8.,  8.],
       [ 9.,  5.],
       [ 4.,  3.]])
In [84]:
np.hstack ((a,b))
Out[84]:
array([[ 7.,  2.,  9.,  5.],
       [ 8.,  8.,  4.,  3.]])
In [86]:
from numpy import newaxis
np.column_stack((a,b))
Out[86]:
array([[ 7.,  2.,  9.,  5.],
       [ 8.,  8.,  4.,  3.]])
In [88]:
a = np.array([4.,2.])

b = np.array([2.,8.])

a[:,newaxis]
Out[88]:
array([[ 4.],
       [ 2.]])
In [89]:
np.column_stack((a[:,newaxis],b[:,newaxis]))
Out[89]:
array([[ 4.,  2.],
       [ 2.,  8.]])
In [90]:
np.vstack((a[:,newaxis],b[:,newaxis]))
Out[90]:
array([[ 4.],
       [ 2.],
       [ 2.],
       [ 8.]])
In [91]:
a = np.floor(10*np.random.random((2,12)))

a
Out[91]:
array([[ 8.,  8.,  8.,  7.,  6.,  6.,  5.,  3.,  6.,  6.,  5.,  1.],
       [ 8.,  3.,  8.,  8.,  3.,  5.,  9.,  3.,  2.,  1.,  0.,  9.]])
In [92]:
np.hsplit(a,3)
Out[92]:
[array([[ 8.,  8.,  8.,  7.],
        [ 8.,  3.,  8.,  8.]]), array([[ 6.,  6.,  5.,  3.],
        [ 3.,  5.,  9.,  3.]]), array([[ 6.,  6.,  5.,  1.],
        [ 2.,  1.,  0.,  9.]])]
In [96]:
np.hsplit(a,(3,5,8))
Out[96]:
[array([[ 8.,  8.,  8.],
        [ 8.,  3.,  8.]]), array([[ 7.,  6.],
        [ 8.,  3.]]), array([[ 6.,  5.,  3.],
        [ 5.,  9.,  3.]]), array([[ 6.,  6.,  5.,  1.],
        [ 2.,  1.,  0.,  9.]])]
In [4]:
a= np.arange (12)

b=a

b is a
Out[4]:
True
In [5]:
b.shape = 3,4
a.shape
Out[5]:
(3, 4)
In [6]:
def f(x):
    
    print(id(x))
    
id(a)

f(a)
2290296487408
In [15]:
c= a.view()

c is a
print (c is a)

c.base is a
print (c.base is a)

c.flags.owndata
print (c.flags.owndata)

c.shape = 2,6
print (a.shape)

print (a)

print (c)

c[0,4] = 1234
print (a)


s = a[:,1:3]

s[:] = 10 

print (a)
False
True
False
(3, 4)
[[   0    1    2    3]
 [1234    5    6    7]
 [   8    9   10   11]]
[[   0    1    2    3 1234    5]
 [   6    7    8    9   10   11]]
[[   0    1    2    3]
 [1234    5    6    7]
 [   8    9   10   11]]
[[   0   10   10    3]
 [1234   10   10    7]
 [   8   10   10   11]]
In [18]:
d = a.copy()

print (d is a)

print (d.base is a)

d[0,0] = 9999
print (a)
False
False
[[   0   10   10    3]
 [1234   10   10    7]
 [   8   10   10   11]]
In [19]:
a = np.arange(12)**2

print (a)

i = np.array ([1,1,3,8,5])

a[i]

print (a[i])
[  0   1   4   9  16  25  36  49  64  81 100 121]
[ 1  1  9 64 25]
In [20]:
j = np.array([[3,4], [9,7]])

a[j]

print (a[j])
[[ 9 16]
 [81 49]]
In [23]:
palette = np.array ([[0,0,0],
                     [255,0,0],
                     [0,255,0],
                     [0,0,255],
                     [255,255,255]])

image = np.array ([[0,1,2,0],
                   [0,3,4,0]])

palette[image]

print (palette[image])
[[[  0   0   0]
  [255   0   0]
  [  0 255   0]
  [  0   0   0]]

 [[  0   0   0]
  [  0   0 255]
  [255 255 255]
  [  0   0   0]]]
In [24]:
a= np.arange(12).reshape(3,4)

print (a)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
In [3]:
a = np.arange(12).reshape(3,4)
print (a)

i = np.array( [ [0,1],                        # indices for the first dim of a
               [1,2] ] )

j = np.array( [ [2,1],                        # indices for the second dim
               [3,3] ] )

a[i,j]                                       # i and j must have equal shape
print(a[i,j])

a[i,2]
print (a[i,2])

a[:,j]                                      # i.e., a[ : , j]
print ("\n",a[:,j])
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[ 2  5]
 [ 7 11]]
[[ 2  6]
 [ 6 10]]

 [[[ 2  1]
  [ 3  3]]

 [[ 6  5]
  [ 7  7]]

 [[10  9]
  [11 11]]]
In [4]:
l = [i,j]
a[l]                                       # equivalent to a[i,j]
print (a[l])
[[ 2  5]
 [ 7 11]]
In [5]:
s = np.array( [i,j] )
# a[s]                                    # not what we want

a[tuple(s)]                                # same as a[i,j]
print ("\n",a[tuple(s)])
 [[ 2  5]
 [ 7 11]]
In [6]:
time = np.linspace(20, 145, 5)                 # time scale
data = np.sin(np.arange(20)).reshape(5,4)      # 4 time-dependent series
print (time)

print (data)

ind = data.argmax(axis=0)                     # index of the maxima for each series
print (ind)

time_max = time[ind]                          # times corresponding to the maxima
print (time_max)


data_max = data[ind, range(data.shape[1])]    # data[ind[0],0], data[ind[1],1]...
print (data_max)

np.all(data_max == data.max(axis=0))
print (np.all(data_max == data.max(axis=0)))
[  20.     51.25   82.5   113.75  145.  ]
[[ 0.          0.84147098  0.90929743  0.14112001]
 [-0.7568025  -0.95892427 -0.2794155   0.6569866 ]
 [ 0.98935825  0.41211849 -0.54402111 -0.99999021]
 [-0.53657292  0.42016704  0.99060736  0.65028784]
 [-0.28790332 -0.96139749 -0.75098725  0.14987721]]
[2 0 3 1]
[  82.5    20.    113.75   51.25]
[ 0.98935825  0.84147098  0.99060736  0.6569866 ]
True
In [7]:
a = np.arange(5)
print (a)

a[[1,3,4]] = 0
print (a)


# However, when the list of indices contains repetitions,
# the assignment is done several times, leaving behind the last value:

a = np.arange(5)
print ("\n",a)

a[[0,0,2]]=[1,2,3]        # at index 0, 1 is placed. Then again at index 0, 1 is replaced by 2. And at index 2, 3 is placed.
print (a)


# This is reasonable enough, but watch out if you want to
# use Python’s += construct, as it may not do what you expect:

a = np.arange(5)
print ("\n",a)
a[[0,0,2]]+=1
print ("\n",a)

#Even though 0 occurs twice in the list of indices,
# the 0th element is only incremented once.
# This is because Python requires “a+=1” to be equivalent to “a = a + 1"
[0 1 2 3 4]
[0 0 2 0 0]

 [0 1 2 3 4]
[2 1 3 3 4]

 [0 1 2 3 4]

 [1 1 3 3 4]
In [8]:
# Indexing with Boolean Arrays

a = np.arange(12).reshape(3,4)
b = a > 4
print (b)                                          # b is a boolean with a's shape

print(a[b])


# This property can be very useful in assignments:
a[b] = 0                                          # All elements of 'a' higher than 4 become 0
print (a)
[[False False False False]
 [False  True  True  True]
 [ True  True  True  True]]
[ 5  6  7  8  9 10 11]
[[0 1 2 3]
 [4 0 0 0]
 [0 0 0 0]]
In [11]:
# You can look at the following example to see how
# to use boolean indexing to generate an image of the Mandelbrot set:

import numpy as np
import matplotlib.pyplot as plt
def mandelbrot( h,w, maxit=20 ):
    """Returns an image of the Mandelbrot fractal of size (h,w)."""
    y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ]
    c = x+y*1j
    z = c
    divtime = maxit + np.zeros(z.shape, dtype=int)
    
    for i in range(maxit):
        z = z**2 + c
        diverge = z*np.conj(z) > 2**2         
        div_now = diverge & (divtime==maxit)  
        divtime[div_now] = i                  
        z[diverge] = 2                        
        
        return divtime
    plt.imshow(mandelbrot(400,400))
    plt.show()
In [12]:
# The second way of indexing with booleans is more similar
# to integer indexing; for each dimension of the array
# we give a 1D boolean array selecting the slices we want:

a = np.arange(12).reshape(3,4)
b1 = np.array([False,True,True])             # first dim selection
b2 = np.array([True,False,True,False])       # second dim selection

a[b1,:]                                      # selecting rows
print (a[b1,:])

a[b1]                                        # same thing
print (a[b1])                

a[:,b2]                                      # selecting columns
print ("\n",a[:,b2])

a[b1,b2]                                     # a weird thing to do
print ("\n",a[b1,b2])
[[ 4  5  6  7]
 [ 8  9 10 11]]
[[ 4  5  6  7]
 [ 8  9 10 11]]

 [[ 0  2]
 [ 4  6]
 [ 8 10]]

 [ 4 10]

Comments

Popular posts from this blog

Pandas Library

Exercise 2 - 3

Matplot LIbrary