Skip to content

Instantly share code, notes, and snippets.

@Audhil
Last active October 17, 2017 13:58
Show Gist options
  • Save Audhil/a1aaefeb52293a92c6e6588a15fe200b to your computer and use it in GitHub Desktop.
Save Audhil/a1aaefeb52293a92c6e6588a15fe200b to your computer and use it in GitHub Desktop.
Hands dirty with Python Numpy arrays- just for future references
Hands dirty with Python Numpy arrays
# Tut @ https://docs.scipy.org/doc/numpy-dev/user/quickstart.html
a = np.arange(22).reshape(2, 11)
print(a)
# [[ 0 1 2 3 4 5 6 7 8 9 10]
# [11 12 13 14 15 16 17 18 19 20 21]]
a.shape
# (2, 11)
a.ndim
# 2
a.dtype.name
# 'int64'
a.itemsize
# 8
a.size
# 22
type(a)
# numpy.ndarray
a < 7
# array([[ True, True, True, True, True, True, True, False, False,
# False, False],
# [False, False, False, False, False, False, False, False, False,
# False, False]], dtype=bool)
b = np.array([(1.5,2,3), (4,5,6)])
# array([[ 1.5, 2. , 3. ],
# [ 4. , 5. , 6. ]])
b = np.array([[1.5, 2, 3], [4, 5, 6]])
# array([[ 1.5, 2. , 3. ],
# [ 4. , 5. , 6. ]])
c = np.array([[1, 2], [3, 4]], dtype=complex)
# array([[ 1.+0.j, 2.+0.j],
# [ 3.+0.j, 4.+0.j]])
np.zeros((3, 4))
# array([[ 0., 0., 0., 0.],
# [ 0., 0., 0., 0.],
# [ 0., 0., 0., 0.]])
np.ones((2, 3, 4), dtype=np.int16)
# array([[[1, 1, 1, 1],
# [1, 1, 1, 1],
# [1, 1, 1, 1]],
# [[1, 1, 1, 1],
# [1, 1, 1, 1],
# [1, 1, 1, 1]]], dtype=int16)
np.empty((2, 3))
"""creates an array whose initial content is random and depends on the state of the memory."""
# array([[ 1.5, 2. , 3. ],
# [ 4. , 5. , 6. ]])
np.arange(10, 30, 5)
# array([10, 15, 20, 25])
np.arange(0, 2, 0.3)
# array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
"""When arange is used with floating point arguments,
it is generally not possible to predict the number of elements obtained, due to the finite floating point precision.
For this reason, it is usually better to use the function linspace that receives as an argument the number of elements that we want"""
np.linspace(0, 2, 9) # 9 numbers from 0 to 2
# array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
from numpy import pi
x = np.linspace(0, 2 * pi, 10)
f = np.sin(x)
print(f)
# [ 0.00000000e+00 6.42787610e-01 9.84807753e-01 8.66025404e-01
# 3.42020143e-01 -3.42020143e-01 -8.66025404e-01 -9.84807753e-01
# -6.42787610e-01 -2.44929360e-16]
np.arange(6)
# array([0, 1, 2, 3, 4, 5]) # 1d array
np.arange(12).reshape(4, 3) # 2d array
# array([[ 0, 1, 2],
# [ 3, 4, 5],
# [ 6, 7, 8],
# [ 9, 10, 11]])
np.arange(24).reshape(2, 3, 4) # 3d array
# array([[[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]],
#
# [[12, 13, 14, 15],
# [16, 17, 18, 19],
# [20, 21, 22, 23]]])
np.arange(10000).reshape(100, 100)
# array([[ 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]])
A = np.array([[1, 1], [0, 1]])
B = np.array([[2, 0], [3, 4]])
A * B # elementwise product
# array([[2, 0],
# [0, 4]])
A.dot(B) # matrix product
# array([[5, 4],
# [3, 4]])
np.dot(A, B) # another matrix product
# array([[5, 4],
# [3, 4]])
np.random.random((2, 3))
# array([[ 0.25684051, 0.51401099, 0.53701769],
# [ 0.19384263, 0.11377185, 0.33986786]])
a = np.ones((2, 3), dtype=int)
b = np.random.random((2, 3))
a *= 3
a
# array([[3, 3, 3],
# [3, 3, 3]])
b += a
b
# array([[ 3.94134554, 3.57795602, 3.72012803],
# [ 3.59781992, 3.13367384, 3.23380899]])
a += b # b is not automatically converted to integer type
a
# TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
a = np.random.random((2, 3))
print(a)
# [[ 0.46939561 0.74113715 0.3278222 ]
# [ 0.7788884 0.43840453 0.67331374]]
print(a.sum())
# 3.4289616403
print(a.max())
# 0.778888399709
print(a.min())
# 0.327822199142
b = np.arange(12).reshape(3, 4)
b
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]])
b.sum(axis=0) # sum of each column
# array([12, 15, 18, 21])
b.sum(axis=1) # sum of each row
# array([ 6, 22, 38])
b.min(axis=1) # min of rows
# array([0, 4, 8])
b.cumsum(axis=0) # cumulative sum along each column
# array([[ 0, 1, 2, 3],
# [ 4, 6, 8, 10],
# [12, 15, 18, 21]])
b.cumsum(axis=1) # cumulative sum along each row
# array([[ 0, 1, 3, 6],
# [ 4, 9, 15, 22],
# [ 8, 17, 27, 38]])
B = np.arange(3)
np.exp(B)
# array([ 1. , 2.71828183, 7.3890561 ])
"""Indexing, Slicing and Iterating"""
# One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences.
a = np.arange(10) ** 3
a
# array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])
a[3]
# 27
a[2:5]
# array([ 8, 27, 64])
a[:4]
# array([ 0, 1, 8, 27])
a[5:]
# array([125, 216, 343, 512, 729])
a[:6:2] = -1000 # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
a
# array([-1000, 1, -1000, 27, -1000, 125, 216, 343, 512, 729])
a[6::2] = -1000
a
# array([ 0, 1, 8, 27, 64, 125, -1000, 343, -1000, 729])
# val = a[::-1] # reversed a
print(val)
# [729 512 343 216 125 64 27 8 1 0]
for i in a:
print('i is %d, val : %d' % (i, i ** (1 / 3.)))
# i is 0, val : 0
# i is 1, val : 1
# i is 8, val : 2
# i is 27, val : 3
# i is 64, val : 3
# i is 125, val : 4
# i is 216, val : 5
# i is 343, val : 6
# i is 512, val : 7
# i is 729, val : 8
"""In case of multi dimensional array"""
def f(x, y):
print('x is \n', x)
print('y is \n', y)
return 10 * x + y
b = np.fromfunction(f, (5, 4), dtype=int)
print('b is \n', b)
# x is [[0 0 0 0]
# [1 1 1 1]
# [2 2 2 2]
# [3 3 3 3]
# [4 4 4 4]]
# y is [[0 1 2 3]
# [0 1 2 3]
# [0 1 2 3]
# [0 1 2 3]
# [0 1 2 3]]
# b is
# array([[ 0, 1, 2, 3],
# [10, 11, 12, 13],
# [20, 21, 22, 23],
# [30, 31, 32, 33],
# [40, 41, 42, 43]])
print(b[2, 3])
# 23
print(b[:5, 1])
# [ 1 11 21 31 41]
print(b[:4, 1])
# [ 1 11 21 31]
print(b[4:, 1])
# [41]
print(b[3:, 1])
# [31 41]
print(b[:, 3])
# [ 3 13 23 33 43]
print(b[1:3, :]) # from row1 to row before end index(here's 2)
# [[10 11 12 13]
# [20 21 22 23]]
# another
def f(x, y):
print('x is \n', x)
print('y is \n', y)
return x + y
c = np.fromfunction(f, (3, 2), dtype=int)
print('c is \n', c)
# x is
# [[0 0]
# [1 1]
# [2 2]]
# y is
# [[0 1]
# [0 1]
# [0 1]]
# c is
# [[0 1]
# [1 2]
# [2 3]]
# When fewer indices are provided than the number of axes, the missing indices are considered complete slices:
print(b[-1]) # the last row. Equivalent to b[-1,:]
# [40 41 42 43]
print(b[2:, ...]) # prints rows from 2nd row
# [[20 21 22 23]
# [30 31 32 33]
# [40 41 42 43]]
print(b[3, ...]) # prints only 3rd row
# [30 31 32 33]
c = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15]])
c
# array([list([0, 1, 2, 3, 4]), list([5, 6, 7, 8, 9]),
# list([10, 11, 12, 13, 14, 15])], dtype=object)
c = np.arange(24).reshape(2, 3, 4)
c
# array([[[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]],
# [[12, 13, 14, 15],
# [16, 17, 18, 19],
# [20, 21, 22, 23]]])
c.shape
# (2, 3, 4)
c[1, ...] # same as c[1,:,:] or c[1]
# array([[12, 13, 14, 15],
# [16, 17, 18, 19],
# [20, 21, 22, 23]])
c[..., 2] # same as c[:,:,2]
# array([[ 2, 6, 10],
# [14, 18, 22]])
c[1::1]
# array([[[12, 13, 14, 15],
# [16, 17, 18, 19],
# [20, 21, 22, 23]]])
c[:1:]
# array([[[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]]])
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]
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
"""Shape Manipulation"""
print(np.floor(np.random.random((3, 4))))
a = np.floor(10 * np.random.random((3, 4)))
print(a)
# array([[ 2., 3., 1., 1.],
# [ 6., 3., 0., 3.],
# [ 1., 2., 6., 9.]])
a.shape
# (3, 4)
"""Reshapes array but doesn't affect the original array"""
a.ravel() # returns the array, flattened
# array([ 6., 9., 8., 4., 6., 4., 1., 2., 9., 5., 2., 3.])
a.reshape(2, 6)
# array([[ 8., 5., 7., 6., 8., 0.],
# [ 8., 8., 0., 2., 6., 1.]])
a.T
# array([[ 6., 8., 1.],
# [ 0., 5., 2.],
# [ 6., 4., 7.],
# [ 3., 6., 0.]])
print(a.shape)
# (3, 4)
print(a.T.shape)
# (4, 3)
"""Reshaping affects the original array"""
print('original array a : \n', a)
a.resize(6, 2)
# original array a :
# [[ 1. 7. 2. 4.]
# [ 2. 1. 5. 9.]
# [ 4. 6. 8. 0.]]
print('resized array a : \n', a)
# resized array a :
# [[ 1. 7.]
# [ 2. 4.]
# [ 2. 1.]
# [ 5. 9.]
# [ 4. 6.]
# [ 8. 0.]]
"""If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated:"""
print('original array a : \n', a)
print('original array a : \n', a.reshape(3, -1))
# original array a :
# [[ 9. 2.]
# [ 9. 8.]
# [ 4. 2.]
# [ 7. 5.]
# [ 8. 1.]
# [ 3. 4.]]
# original array a :
# [[ 9. 2. 9. 8.]
# [ 4. 2. 7. 5.]
# [ 8. 1. 3. 4.]]
"""Several arrays can be stacked together along different axes:"""
a = np.floor(10 * np.random.random((2, 2)))
b = np.floor(10 * np.random.random((2, 2)))
print('this is a : \n', a)
print('this is b : \n', b)
print('this is vstack : \n', np.vstack((a, b)))
print('this is hstack : \n', np.hstack((a, b)))
# this is a :
# [[ 6. 6.]
# [ 9. 5.]]
# this is b :
# [[ 5. 8.]
# [ 7. 1.]]
# this is vstack :
# [[ 6. 6.]
# [ 9. 5.]
# [ 5. 8.]
# [ 7. 1.]]
# this is hstack :
# [[ 6. 6. 5. 8.]
# [ 9. 5. 7. 1.]]
"""The function column_stack stacks 1D arrays as columns into a 2D array. It is equivalent to vstack only for 1D arrays:"""
print('this is a : \n', a)
print('this is b : \n', b)
np.column_stack((a, b)) # With 2D arrays
# this is a :
# [[ 6. 6.]
# [ 9. 5.]]
# this is b :
# [[ 5. 8.]
# [ 7. 1.]]
# array([[ 6., 6., 5., 8.],
# [ 9., 5., 7., 1.]])
from numpy import newaxis
a = np.array([4., 2.])
b = np.array([3., 8.])
print('this is a : \n', a)
print('this is b : \n', b)
# this is a :
# [ 4. 2.]
# this is b :
# [ 3. 8.]
a[:, newaxis]
# array([[ 4.],
# [ 2.]])
a[newaxis, :]
# array([[ 4., 2.]])
b[:, newaxis]
# array([[ 3.],
# [ 8.]])
b[newaxis, newaxis]
# array([[[ 3., 8.]]])
b[newaxis, :]
# [ 3. 8.]
np.column_stack((a[:, newaxis], b[:, newaxis]))
# array([[ 4., 3.],
# [ 2., 8.]])
np.vstack((a[:, newaxis], b[:, newaxis])) # The behavior of vstack is different
# array([[ 4.],
# [ 2.],
# [ 3.],
# [ 8.]])
"""In complex cases, r_ and c_ are useful for creating arrays by stacking numbers along one axis.
They allow the use of range literals (”:”)"""
np.r_[1:4, 0, 5]
# array([1, 2, 3, 0, 5])
"""Splitting one array into several smaller ones"""
a = np.floor(10 * np.random.random((2, 12)))
print('original a : \n', a)
# original a :
# [[ 6. 6. 1. 6. 3. 1. 2. 8. 2. 5. 7. 3.]
# [ 8. 6. 8. 9. 1. 5. 8. 6. 8. 2. 3. 2.]]
np.hsplit(a, 4)
# [array([[ 6., 6., 1.],
# [ 8., 6., 8.]]),
# array([[ 6., 3., 1.],
# [ 9., 1., 5.]]),
# array([[ 2., 8., 2.],
# [ 8., 6., 8.]]),
# array([[ 5., 7., 3.],
# [ 2., 3., 2.]])]
np.hsplit(a, (3, 4)) # Split a after the third and the fourth column
# original a :
# [[ 9. 5. 7. 6. 8. 0. 6. 5. 4. 6. 9. 3.]
# [ 1. 1. 8. 5. 6. 5. 2. 7. 2. 0. 6. 2.]]
# [array([[9., 5., 7.],
# [1., 1., 8.]]),
# array([[6.],
# [5.]]),
# array([[8., 0., 6., 5., 4., 6., 9., 3.],
# [6., 5., 2., 7., 2., 0., 6., 2.]])]
"""Copies and Views"""
a = np.arange(12)
b = a # no new object is created
b is a # a and b are two names for the same ndarray object
# True
print(a.shape)
(12,)
print(b.shape)
(12,)
b.shape = 3, 4 # changes shape of a
print('b.shape : ',b.shape)
# b.shape : (3, 4)
print('a.shape : ',a.shape)
# a.shape : (3, 4)
"""Python passes mutable objects as references, so function calls make no copy."""
def f(x):
print(id(x))
print('id(a) : ', id(a)) # id is a unique identifier of an object
print('f(a) : ', f(a))
# id(a) : 4841149344
# 4841149344
# f(a) : None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment