Numpy
A Python library that is used for scientific computation over arrays.
It provides a high-performance multidimensional array object, and tools for working with these arrays.
A numpy array is a grid of values and all values have same data type.
It saves memory and speed up the computation.
Import Numpy
In [112]:
import numpy as np
Create Numpy array
In [15]:
# 1D array
d1 = np.array([1, 2, 3])
print('1D dimensional array: \n ', d1)
# 2D array
d2 = np.array(
[
[1, 2, 3],
[5, 6, 7]
]
)
print()
print('2D dimensional array: \n ', d2)
# 3D array
d3 = np.array(
[
[
[1, 2, 3],
[5, 6, 7]
],[
[8, 9, 10],
[11, 12, 13]
]
]
)
print()
print('3D dimensional array: \n ', d3)
1D dimensional array:
[1 2 3]
2D dimensional array:
[[1 2 3]
[5 6 7]]
3D dimensional array:
[[[ 1 2 3]
[ 5 6 7]]
[[ 8 9 10]
[11 12 13]]]
Get shape of an array/matrix
In [19]:
print('Shape of 1D dimensional array: ', d1.shape)
print('Shape of 2D dimensional array: ', d2.shape)
print('Shape of 3D dimensional array: ', d3.shape)
Shape of 1D dimensional array: (3,)
Shape of 2D dimensional array: (2, 3)
Shape of 3D dimensional array: (2, 2, 3)
Create a range between 1 and 10 and step by 2.
np.arange(start, end, step)
In [22]:
r = np.arange(1, 10, 2)
print(r)
[1 3 5 7 9]
Reshape an array
In [134]:
# Reshape 1D
d1 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print('Reshape 1D array into 2 rows and 5 columns: ')
print(d1.reshape(2, 5))
print()
# Reshape 2D
d2 = np.array(
[
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]
]
)
print('Reshape 2D 2x5 into 5x2')
print(d2.reshape(5, 2))
print()
# Reshape 3D
d3 = np.array(
[
[
[1, 2, 3],
[6, 7, 8]
],
[
[1, 2, 3],
[6, 7, 8]
]
]
)
print('Reshape 3D 2x2x3 into 2x3x2')
print(d3.reshape(2, 3, 2))
Reshape 1D array into 2 rows and 5 columns:
[[ 1 2 3 4 5]
[ 6 7 8 9 10]]
Reshape 2D 2x5 into 5x2
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]]
Reshape 3D 2x2x3 into 2x3x2
[[[1 2]
[3 6]
[7 8]]
[[1 2]
[3 6]
[7 8]]]
Linspace
np.linspace(start, end, array_size)
Create a numpy array of equal sized values based on number of sample given.
In [135]:
print('Example 1: ')
l = np.linspace(1, 10, 10)
print(l)
print()
print('Example 2:')
l = np.linspace(1, 10, 8)
print(l)
Example 1:
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
Example 2:
[ 1. 2.28571429 3.57142857 4.85714286 6.14285714 7.42857143
8.71428571 10. ]
Resize
Change the shape of array in place, unlike shape
In [136]:
l = np.linspace(1, 10, 8)
l.resize(4,2)
print('Resize to 4x2: ')
print(l)
Resize to 4x2:
[[ 1. 2.28571429]
[ 3.57142857 4.85714286]
[ 6.14285714 7.42857143]
[ 8.71428571 10. ]]
Create empty array
Return arbitary values that can be changed later.
Use np.zeros() to create zero defined array for better use. Check further cells.
In [137]:
x = np.empty((2,2))
print(x)
x[0]
[[1.28822975e-231 1.28822975e-231]
[1.28822975e-231 2.82472626e-309]]
Out[137]:
array([1.28822975e-231, 1.28822975e-231])
Zeros values in array.
Create an array that contains only Zeros values.
In [138]:
# 1D Zeros array
x = np.zeros(10)
print('1D Zeros array: ')
print(x)
print()
# 2D zeros array
x = np.zeros((2, 3))
print('2D Zeros array: ')
print(x)
1D Zeros array:
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
2D Zeros array:
[[0. 0. 0.]
[0. 0. 0.]]
Ones values in array.
Create an array that contains only ones values.
In [139]:
# 1D ones array
x = np.ones(10)
print('1D ones array: ')
print(x)
print()
# 2D ones array
x = np.ones((2, 3))
print('2D ones array: ')
print(x)
1D ones array:
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
2D ones array:
[[1. 1. 1.]
[1. 1. 1.]]
Diagonal matrix
Create a diagonal matrix with diagonal values are 1.
In [141]:
np.eye(3)
Out[141]:
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
Constant values
Fill matrix with same values.
Values can be changed.
In [142]:
np.full((2,2), 5)
Out[142]:
array([[5, 5],
[5, 5]])
In [187]:
## Random initialize values.
print('Create 1D four random numbers:')
print(np.random.random(4))
print()
print('Generate a random integer between 1 and 10: ')
print(np.random.randint(1, 10))
print()
print('Generate multiple dimension random integer for shape 2x3: ')
print(np.random.randn(2, 3))
print()
# Seed value is used for randomize algorithm. Randomize algorithm gives different result
s on every execution.
print('Seed value: 5')
np.random.seed(5)
print()
# Shuffles the values of numpy array in place.
print('Shuffle: ')
x = np.array([1, 2, 3, 4, 5])
print('Before shuffling, x: ', x)
np.random.shuffle(x)
print('After shuffled, x: ', x)
Create 1D four random numbers:
[0.3637369 0.979445 0.08982104 0.39673661]
Generate a random integer between 1 and 10:
1
Generate multiple dimension random integer for shape 2x3:
[[-1.88576241 0.17092537 -0.40309331]
[ 1.63762849 -0.60529785 -1.59441507]]
Seed value: 5
Shuffle:
Before shuffling, x: [1 2 3 4 5]
After shuffled, x: [5 1 2 3 4]
After shuffled, x: [5 1 2 3 4]
In [158]:
x
Out[158]:
array([[1., 1., 1.],
[1., 1., 1.]])
Numpy Datatypes:
Numpy type Description
np.int8 Byte (-128 to 127)
np.int16 Integer (-32768 to 32767)
np.int32 Integer (-2147483648 to 2147483647)
np.int64 Integer (-9223372036854775808 to 9223372036854775807)
np.float16 Standard double-precision floating point
np.float32 Standard double-precision floating point
np.float64 / np.float_ Standard double-precision floating point
np.bool_ Boolean (True or False) stored as a byte
np.str _ Fixed-length string type
np.bytes _ bytes like object
In [44]:
# Create an numpy array based on numpy data type
x = np.array([1, 2], dtype=np.int8)
x.dtype
Out[44]:
dtype('int8')
Inspect an array
In [57]:
x = np.array([[1, 2], [3, 4]])
# Get shape of an array
print('Shape: ', x.shape)
print()
# Get length of an array
print('Length: ', len(x))
print()
# Get array dimension
print('Dimension: ', x.ndim)
print()
# Get array size
print('Size: ', x.size)
print()
# Get numpy data type
print('Data type: ', x.dtype)
print()
# Convert data type to different data type
print('Convert to data type: ')
x = x.astype('int8')
print(x)
print('Type: ', x.dtype)
Shape: (2, 2)
Length: 2
Dimension: 2
Size: 4
Data type: int64
Convert to data type:
[[1 2]
[3 4]]
Type: int8
Sorting
In [77]:
# Sort 1D array
x = np.array([1, 4, 3, 2])
x.sort()
# x = list(reversed(x)) # Descending is possible using reversed() only.
print('Sorted 1D array: ', x)
print()
# Sort 2D array
x = np.array([[1, 3], [5, 4]])
x.sort()
print('Sorted 2D array: ', x)
Sorted 1D array: [1 2 3 4]
Sorted 2D array: [[1 3]
[4 5]]
Comparison
In [88]:
a = np.array([1, 2, 4, 5])
b = np.array([1, 3, 1, 5])
# Entire array comparision
print('Entire array comparision')
print(np.array_equal(a, b))
print()
# Element-wise comparision
print('Element-wise comparision')
print('Equals to: ', a==b)
print('Greater than and equals to: ', a>=b)
print('Less than and equals to: ', a<=b)
Entire array comparision
False
Element-wise comparision
Equals to: [ True False False True]
Greater than and equals to: [ True False True True]
Less than and equals to: [ True True False True]
Arihmetic operations
In [98]:
In [98]:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print('\n Addition:', a+b) # OR np.add(a, b)
print('\n Substraction:', b-a) # OR np.sub(b, a)
print('\n Multiplication:', a*b) # OR np.multiply(a, b)
print('\n Division:', b/a) # OR np.divide(b, a)
print('\n Exponentiation:', np.exp(a))
print('\n Square root:', np.sqrt(a))
print('\n sin:', np.sin(a))
print('\n cos:', np.cos(a))
print('\n Dot Product:', np.dot(a, b)) # OR a.dot(b)
# Natural logarithm is the inverse of the exp(), so that log(exp(x)) = x.
print('\n Natural logarithm:', np.log(a))
# 10**z = a, where z is the output of np.log(a) and a is the input array
print('\n Base 10 logarithm:', np.log10(a))
# 2**z = a
print('\n Base 2 logarithm:', np.log2(a))
# exp(z) = 1 + a
print('\n Natural logarithm of one plus:', np.log2(a))
Addition: [5 7 9]
Substraction: [3 3 3]
Multiplication: [ 4 10 18]
Division: [4. 2.5 2. ]
Exponentiation: [ 2.71828183 7.3890561 20.08553692]
Square root: [1. 1.41421356 1.73205081]
sin: [0.84147098 0.90929743 0.14112001]
cos: [ 0.54030231 -0.41614684 -0.9899925 ]
Dot Product: 32
Natural logarithm: [0. 0.69314718 1.09861229]
Base 10 logarithm: [0. 0.30103 0.47712125]
Base 2 logarithm: [0. 1. 1.5849625]
Natural logarithm of one plus: [0. 1. 1.5849625]
Statistics
In [103]:
x = [1, 2, 3]
print('\n Sum: ', np.sum(a))
print('\n Min: ', np.min(a))
print('\n Max: ', np.max(a))
print('\n Cummulative Sum: ', np.cumsum(a))
print('\n Mean: ', np.mean(a))
print('\n Median: ', np.median(a))
print('\n Correlation coefficient: ', np.corrcoef(a))
print('\n Standard deviation: ', np.std(a))
Sum: 6
Min: 1
Max: 3
Cummulative Sum: [1 3 6]
Mean: 2.0
Median: 2.0
Correlation coefficient: 1.0
Standard deviation: 0.816496580927726
Indexing and Slicing
In [127]:
x = np.array([1, 2, 3, 4])
print("Select element at index 2nd")
print(x[2])
print()
x = np.array([[1, 2], [3, 4]])
print("Select element at row 2nd and at column 1st")
print(x[1][0])
print()
x = np.array([1, 2, 3, 4])
print("Condition based indexing")
print(x[x<3])
Select element at index 2nd
3
Select element at row 2nd and at column 1st
3
Condition based indexing
[1 2]
In [123]:
x = np.array([1, 2, 3, 4, 5])
print("Slicing over 1D array: ")
print(x[1: 3])
print()
x = np.array([
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]
])
print("Slicing over 2D array: Select elements at row 0th and 1st and in column 3rd")
print(x[0:2, 3])
print()
print("Slicing over 2D array: Select 0th row.")
print(x[0:1])
Slicing over 1D array:
[2 3]
Slicing over 2D array: Select elements at row 0th and 1st and in column 3rd
[4 9]
Slicing over 2D array: Select 0th row.
[[1 2 3 4 5]]
Array Maninpulation
In [ ]:
## Transpose array:
x = np.array([
[1, 2, 3],
[6, 7, 8]
])
print(np.transpose(x)) # OR x.T
print()
print("Flatten the array: Convert 2D array to 1D.")
print(x.ravel())
In [143]:
x = np.array([
[1, 2, 3],
[6, 7, 8]
])
print(x)
print()
print("Appending element to array and flatten it.")
print(np.append(x, 3))
print()
print("Insert an element to array and flatten it.")
print(np.insert(x, 2, 11))
print()
print("Delete an element from an array and flatten it.")
print(np.delete(x, 2))
[[1 2 3]
[6 7 8]]
Appending element to array and flatten it.
[1 2 3 6 7 8 3]
Insert an element to array and flatten it.
[ 1 2 11 3 6 7 8]
Delete an element from an array and flatten it.
[1 2 6 7 8]
Combine arrays
In [160]:
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print()
print('Append to the rows')
print(np.concatenate((a, b), axis=0)) # axis=0 add as rows, axis=1, add as columns
print()
print('Append to the columns')
print(np.concatenate((a, b), axis=1)) # axis=0 add as rows, axis=1, add as columns
Append to the rows
[[1 2]
[3 4]
[5 6]
[7 8]]
Append to the columns
[[1 2 5 6]
[3 4 7 8]]
In [161]:
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print()
print('vstack: Row-wise concatenation')
print(np.vstack((a, b)))
print()
print('hstack: Column-wise concatenation')
print(np.hstack((a, b)))
vstack: Row-wise concatenation
[[1 2]
[3 4]
[5 6]
[7 8]]
hstack: Column-wise concatenation
[[1 2 5 6]
[3 4 7 8]]
Array splitting
In [181]:
a = np.array(
[
[1, 2],
[3, 4]
]
)
print()
print('Split array into 2 sub-arrays')
print(np.split(a, 2))
print()
print('Split array horizontally at 2nd index to create sub arrays')
print(np.hsplit(a, 2))
print()
print('Split array vertically at 2nd index to create sub arrays')
print(np.vsplit(a, 2))
Split array into 2 sub-arrays
[array([[1, 2]]), array([[3, 4]])]
Split array horizontally at 2nd index to create sub arrays
[array([[1],
[3]]), array([[2],
[4]])]
Split array vertically at 2nd index to create sub arrays
[array([[1, 2]]), array([[3, 4]])]
In [ ]: