Numpy
Numpy
Import Numpy
In [112]:
import numpy as np
# 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]]]
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))
[[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. ]]
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])
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.]]
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()
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)
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
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()
Shape: (2, 2)
Length: 2
Dimension: 2
Size: 4
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]
Comparison
In [88]:
a = np.array([1, 2, 4, 5])
b = np.array([1, 3, 1, 5])
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])
Addition: [5 7 9]
Substraction: [3 3 3]
Multiplication: [ 4 10 18]
Dot Product: 32
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
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])
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 2D array: Select elements at row 0th and 1st and in column 3rd
[4 9]
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]]
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
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)))
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))
In [ ]: