https://numpy.
org/
NumPy is a Python package that stands for Numerical Python. NumPy is a library for the Python programming
language, adding support for large, multi-dimensional arrays and matrices, along with an extensive collection of
high-level mathematical functions to operate on these arrays.
Why NumPy?
The very basic question that might come to our mind is why we use NumPy when we already have the list data
structure in Python; well, we have got many reasons to use NumPy over a list, but the very basic reason is the
use of less space and time.
Numpy is faster:
It provides efficient storage
How to install NumPy?
Go to anaconda cmd and type "pip install numpy" (internet connection required), pip is a package manager.
Array creation
There are 5 general mechanisms for creating arrays:
1- Conversion from other Python structures (e.g., lists, tuples).
2- Intrinsic numpy array array creation objects (e.g., arange, ones, zeros, etc).
3- Reading arrays from disk, either from standard or custom formats.
4- Creating arrays from raw bytes through the use of strings or buffers.
5- Use of special library functions (e.g., random).
Method-1: From List
In [1]: # How to import NumPy
import numpy as np
In [2]: # Create a NumPy 1-D array from List
a = [1,2,20,9]
a1 = np.array(a)
a1
array([ 1, 2, 20, 9])
Out[2]:
In [3]: # Set and datatype of 8 bit
a2 = np.array([1,2,20,9], np.int8)
a2
array([ 1, 2, 20, 9], dtype=int8)
Out[3]:
In [4]: # Set a large number to 8 bit data type
# It return some garbage value or error at that large value
a3 = np.array([1,2,3799862,9], np.int8)
a3
array([ 1, 2, 54, 9], dtype=int8)
Out[4]:
In [5]: # To overcome this issue change dtype to int32 or int64
a4 = np.array([1,2,3799862,9], np.int32)
a4
array([ 1, 2, 3799862, 9])
Out[5]:
In [6]: # How to access any element from 1-D array
a5 = np.array([1,2,5,9], np.int8)
a5[0]
1
Out[6]:
In [7]: # Create a NumPy 2-D array from List
a6 = np.array([[1,2,3],[4,5,6]])
a6
array([[1, 2, 3],
Out[7]:
[4, 5, 6]])
In [8]: # Create a NumPy 3-D array from List
a7 = np.array([[[1,2,3],[4,5,6],[7,8,9]]])
a7
array([[[1, 2, 3],
Out[8]:
[4, 5, 6],
[7, 8, 9]]])
In [9]: # Find shape of an 1-D array
a8 = np.array([1,3,5,9])
a8.shape
(4,)
Out[9]:
In [10]: # Find shape of an 2-D array
a9 = np.array([[1,2,3],[4,5,6]])
a9.shape
(2, 3)
Out[10]:
In [11]: # Find size of an 1-D array
a10 = np.array([1,3,5,9])
a10.size
4
Out[11]:
In [12]: # Find size of an 2-D array
a11 = np.array([[1,2,3],[4,5,6]])
a11.size
6
Out[12]:
In [13]: # Find dtype of an array, default dtype = int32
a12 = np.array([1,24,5,9])
a12.dtype
dtype('int32')
Out[13]:
In [14]: #change an element in an array
a13 = np.array([1,5,7,8])
a13[0]=3
a13
array([3, 5, 7, 8])
Out[14]:
Method-2: Intrinsic (Zero, Ones, Arrange)
In [15]: # array using zero attribute
z=np.zeros((3,3))
z
array([[0., 0., 0.],
Out[15]:
[0., 0., 0.],
[0., 0., 0.]])
In [16]: # 3-D array has by deafult dtype float64
z.dtype
dtype('float64')
Out[16]:
In [17]: z.shape
(3, 3)
Out[17]:
In [18]: # array using arange attribute
# It returns from 0 to n-1 array
r=np.arange(5)
r
array([0, 1, 2, 3, 4])
Out[18]:
In [19]: # Arange, Reshape, Ravel
ar=np.arange(99)
ar
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
Out[19]:
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98])
In [20]: # Reshape
ar.reshape(3,33)
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
Out[20]:
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32],
[33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65],
[66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
98]])
In [21]: # Can't reshape of unmatched order
ar.reshape(3,31)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5052/2691225820.py in <module>
1 # Can't reshape of unmatched order
----> 2 ar.reshape(3,31)
ValueError: cannot reshape array of size 99 into shape (3,31)
In [22]: arr = ar.ravel()
arr
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
Out[22]:
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98])
In [23]: # array using lspace attribute
# It return equally linearly space 10 elements
lspace=np.linspace(1,5,10)
lspace
array([1. , 1.44444444, 1.88888889, 2.33333333, 2.77777778,
Out[23]:
3.22222222, 3.66666667, 4.11111111, 4.55555556, 5. ])
In [24]:
# Empty array/matrics
e=np.empty((3,3))
e
array([[0., 0., 0.],
Out[24]:
[0., 0., 0.],
[0., 0., 0.]])
In [25]: # Identity array/matrics
i=np.identity(3)
i
array([[1., 0., 0.],
Out[25]:
[0., 1., 0.],
[0., 0., 1.]])
In [26]: o=np.ones((3,3))
o
array([[1., 1., 1.],
Out[26]:
[1., 1., 1.],
[1., 1., 1.]])
Axis in NumPy
Cartesian Coordinate Systems
You probably remember this, but just so we’re clear, let’s take a look at a simple Cartesian coordinate system.
Just like coordinate systems, NumPy arrays also have axes
1D-Array = [1,2,3,4,5] --> No. of Axis 1
2D-Array = [[1,2],[3,4]] --> No. of Axis 2
In [27]: # Create a NumPy 2-D array from List
x = [[1,2,3],[4,5,6]]
x = np.array(x)
x
array([[1, 2, 3],
Out[27]:
[4, 5, 6]])
In [28]: # Sum of 2-D array at axis 0
x.sum(axis=0)
array([5, 7, 9])
Out[28]:
In [29]: # Sum of 2-D array at axis 1
x.sum(axis=1)
array([ 6, 15])
Out[29]:
In [30]: # Transpose of a 2-D array
x.T
array([[1, 4],
Out[30]:
[2, 5],
[3, 6]])
In [31]: # Find dimension of an array
x.ndim
2
Out[31]:
In [32]: # find no of bytes taken in memory
x.nbytes
24
Out[32]:
argmax() function in NumPy
In [33]: # find element of max index position in an 1-D array
one = np.array([1,3,4634,3])
one.argmax()
2
Out[33]:
In [34]: # find element of min index position in an 1-D array
one.argmin()
0
Out[34]:
In [35]: # sort an array indexing in asending order
one.argsort()
array([0, 1, 3, 2], dtype=int64)
Out[35]:
In [36]: # find element of max index position in an 2-D array
two = np.array([[1,2,3],[4,5,6],[7,1,0]])
two.argmax()
6
Out[36]:
In [37]: # find element of min index position in an 2-D array
two.argmin()
8
Out[37]:
In [38]: # find element of mix index position in an 2-D array at axis 0
two.argmax(axis=0)
array([2, 1, 1], dtype=int64)
Out[38]:
In [39]: # find element of min index position in an 2-D array at axis 1
two.argmax(axis=1)
array([2, 2, 0], dtype=int64)
Out[39]:
Prove how NumPy is storage efficient
Proof:
In [40]: import sys
In [41]: python_array = [0,4,55,2]
numpy_array = np.array(python_array)
In [42]: sys.getsizeof(1)*len(python_array)
112
Out[42]:
In [43]: numpy_array.itemsize*numpy_array.size
16
Out[43]:
NumPy TASK:
Q1: How to create an empty and a full NumPy 2D-Array of shape (3,4)? Take any integer value for full NumPy
2D-Array.
Q2: Create a NumPy Array that return evenly spaced numbers over a specified interval. Take 1 as start value, 12
as end value and number of samples are 12.
Q3: Create a NumPy Array that return evenly spaced values within a given interval. Take 99 as interval value. Can
we reshape this array into shape (3, 31)?
Q4: How to find elements of min index position in an given 2D array at axis 1, [[1,2,3],[4,5,6],[7,1,0]] Hint: argmin()
Q5: How to sort elements w.r.t indexing in asending order of given 2D array at axis 0, [[1,2,3],[4,5,6],[7,1,0]] Hint:
argsort()
In [44]: # Solution Q1:
import numpy as np
# Create an empty array
empa = np.empty((3, 4), dtype=int)
print("Empty Array")
print(empa)
# Create a full array
flla = np.full([3, 4], 56, dtype=int)
print("\n Full Array")
print(flla)
Empty Array
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
Full Array
[[56 56 56 56]
[56 56 56 56]
[56 56 56 56]]
In [45]: # Solution Q2:
lspace=np.linspace(1,5,12)
lspace
array([1. , 1.36363636, 1.72727273, 2.09090909, 2.45454545,
Out[45]:
2.81818182, 3.18181818, 3.54545455, 3.90909091, 4.27272727,
4.63636364, 5. ])
In [46]: # Solution Q3:
arr = np.arange(99)
arr
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
Out[46]:
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98])
In [47]: arr=arr.reshape(3,31)
arr
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5052/1710490344.py in <module>
----> 1 arr=arr.reshape(3,31)
2 arr
ValueError: cannot reshape array of size 99 into shape (3,31)
In [48]: # Solution Q4:
two = np.array([[1,2,3],[4,5,6],[7,1,0]])
two.argmax(axis=1)
array([2, 2, 0], dtype=int64)
Out[48]:
In [49]: # Solution Q5:
two = np.array([[1,2,3],[4,5,6],[7,1,0]])
two.argsort(axis=0)
array([[0, 2, 2],
Out[49]:
[1, 0, 0],
[2, 1, 1]], dtype=int64)