What is NumPy
Basics
Attributes : data types, size, shape, memory consumption
Indexing
Slicing
Reshaping
Joining and splitting
Masking
Broadcasting
Structured arrays
Example : Attributes
import numpy as np
dir(np)
print(np.__version__)
nparray = np.arange(10)
print (nparray)
np.random.seed(0)
x = np.random.randint(10, size=8)
x.ndim
x.shape
x.size
x.dtype
x.dtype.str
x.itemsize
x.nbytes
x.real # for complex numbers, this returns the real part
x.imag # for complex numbers, this returns the imaginary part
x.size
Example : Indexing
import numpy as np
np.random.seed(0)
x = np.random.randint(10, size=8)
x[1]
x[-1]
x[-2]
x[0] = 3.456 # will be truncated, dtype is int32
y = np.random.randint(10, size=(5,5))
y[1,2]
y[1][2] # same as y[1,2]
y[2,-1]
y[0,1] = 20
y
Example : Slicing
import numpy as np
z = np.arange(10)
z[:5]
z[3:]
z[2:8]
z[::3] # every third element
z[1::2] # every other, odd elements
z[::-1] # all elements in reversed order
z[9::-4] # every fourth element in reversed order
Example : Multi-dimensional subarrays
import numpy as np
np.random.seed(0)
x = np.random.randint(10, size=(3,4,3))
x
x[:2, :3] # sub array taking 2 rows and three columns
x[:3, ::2] # sub array taking 3 rows and every other column
x[::-1, ::-1] # sub array reversing rows and columns
x[::-1] # reverse the whole array
# accessing single row or column
x[0, :] # first row, same as x[0]
x[:, 0] # first column
Example : Creating copies of subarrays
# Slice sub arrays without copying will modify the original array
# when you modify the subarray
import numpy as np
np.random.seed(0)
x = np.random.randint(10, size=(3,4,3))
x
y = x[:2, :2]
y[0,0] = 12345
print(y)
print(x)
# create copy of x
z = x[:4,:4].copy()
# now try to change z and check x
q = z.resize((1,2))
q.ravel() # flatten as a view, point to same object
q.flatten() # same as ravel, and allocate new memory
p = q.view() # p and q point to same object
id(p)
id(q)
p is q
r = np.insert(p, 1, 505, axis=0)
s = np.empty(p.shape) # create new array in same shape as 'p'
np.copyto( s, q )
np.delete( q, 1, axis=0 )
Example : Reshaping
import numpy as np
x = np.arange(1,10).reshape(3,3)
y = np.arange(1,17).reshape(4,4)
# size of np.arange must match size of the reshaped array
x1 = np.array([1,2,3])
x1.reshape((1,3))
x1[np.newaxis, :] # row vector using newaxis
x1[:, np.newaxis] # column vector using newaxis
x1.reshape((3,1)) # column vector using reshape
Example : Concatenation and Stacking of arrays
import numpy as np
x = np.arange(5)
xtriple = x*3
print(xtriple)
y = np.arange(10)
z = np.concatenate([x,y])
q = np.concatenate([x,y,z])
x2d = np.array([[1,2,3],[4,5,6]])
y2d = np.concatenate ([x2d,x2d] )
z2d = np.concatenate ([x2d,x2d], axis=1)
# using np.hstack or np.vstack
# np.dstack will stack along the third axis
x = np.array([1,2,3])
x2d = np.array([[9,9,9],[8,7,6]])
xx = np.vstack([x, x3d])
y = np.array([[3],[3]])
yy = np.hstack([x2d, y])
column_stack((x,y))
row_stack((x,y))
a = arange(4)reshape(2,2)
b = np.array([[5,6]])
hstack((a,b)) # same as np.append(a,b,axis=1) # append along y, change (*, y, *) shape
vstack((a,b)) # same as np.append(a,b,axis=2) # append along x, change (*, *, x) shape
concatenate((a,b), axis=0) # same as vstack
dstack((a,b)) # depth stacking
column_stack((a,b)) # stack 1d array column-wise
row_stack((a,b))
Example : Splitting, squeezing and reshaping
import numpy as np
x = [1,2,3,4,5,6,7,8]
a,b,c = np.split(x, [3,5])
# np.hsplit and np.vsplit
x2d = np.arange(16).reshape((4,4))
upper_ary, lower_ary = np.vsplit(x2d,[2])
# check upper and lower arrays
left_ary, right_ary = np.hsplit(x2d,[2])
# check left and right arrays
X = np.arange(27).reshape(3,3,3)
# split()
# hsplit()
# vsplit()
# dsplit()
hsplit(X)
split(X, 3, axis=1) # same as hsplit(X,3)
split(X, 3, axis=0) # same as vsplit(X,3)
dsplit(array,3) # deep split
Example : linespace, zeros, ones
import numpy as np
# notice linspac euse closed interval where end point is included
ary = np.linspace(7,26,9)
ary = np.linspace(7,26,9, retstep=True)
ary = np.zeros(5, dtype='int32')
np.ones((7,8))
# default dtype for zeros and ones is float
# default dtype for arange and linspace is int
ary = np.ones((2,2))
ary.squeeze()
Example : random
import numpy as np
# notice linspac euse closed interval where end point is included
ary = np.random.random.rand() ## uniform distribution
ary = np.random.random.randn() ## gaussian normal distribution
np.random.random.seed(0) ## not thread safe
Example : Mathematical operators
import numpy as np
m0 = np.ones(2)
m1 = np.ones(2)*3
np.inner (m0,m1)
m0 = np.arange(4).reshape(2,2)
m1 = np.arange(8).reshape(2,4)
np.dot (m0,m1)
nparray.shape(1,2,3)
nparray.sum(axis=2)
np.set_printoptions(precision=4)
Example : logical operators
import numpy as np
ary = np.arange(12).reshape(3,4)
x0 = 0 == (ary % 3)
x1 = ary > 3
x2 = np.logical_and (x0, x1)
# y and z would result in same matrix
y = ary[x2]
z = ary[ary > 3]
Example : structured array
import numpy as np
person_data_def = [('name','s10'), ('height','f8'), ('weight','f8'), ('age','i2')]
people_array = np.zeros((4), dtype=person_data_def)
Example : Comparison
import numpy as np
x = [1,2,3,4,5]
print (x*2)
y = np.array([1,2,3,4,5])
print (y*2)
# to get the same result for x
for i, v in enumerate (x):
x[i] *= 2
print(x)