NumPy is a opensource python numerical library used for mathematical computing in data science. In this article I am going to tell you the introduction to the NumPy and how you can use it for mathematical computing.
Table of Contents
Table Of Content
So, let me tell you in brief that what you will be learning by the end of this reading:
- Why NumPy and types of NumPy array
- List vs NumPy (Numerical Python) Array and we will see how NumPy is better than a Python list
- Indexing and slicing in NumPy Array
- Classes & attributes of NumPy Array
- Basic Operations of NumPy Array
- Linear Algebra Using NumPy Array
Why NumPy and types of NumPy array:
NumPy allows multidimensional arrays where we can perform mathematical operations.
- NumPy has smaller memory consumption and better run-time behavior. A random integer NumPy array holds a memory as (96 + n * 8) bytes
- NumPy can perform both element-wise and mathematical computations.
- NumPy can be used to perform linear algebraic operations, Fourier transformations, and random number generation.
- The multidimensional NumPy array can add, remove, change any element of it.
List vs NumPy (Numerical Python) Array
List: It is a type of built-in data structure in python to hold any number and types of values. We can perform any kind of element level append, delete, replace operations in the list.
- List can hold any datatype of elements.
- We can perform operations on individual elements of a list, But we can not do numerical math operations in a list.
- We don’t need to define a list as it is built-in.
- Storing data in a list is less compact than NumPy array.
Check the code below to understand the Python List.
>>> my_list = [['Pritam', 28, 'Indian'], ['Aaru', 23, 'India']] >>> my_list [['Pritam', 28, 'Indian'], ['Aaru', 23, 'India']]
Now check the code.
>>> population = [1234, 567, 890, 432] >>> avr_age = [22, 32, 43, 29] >>> total_age = population * avr_age Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't multiply sequence by non-int of type 'list'
You will see an error in the above code because we are trying to do numerical mathematical operation.
Now let’s understand the NumPy Array.
NumPy Array: NumPy can be used with arrays which are called ndarray. We can create a NumPy ndarray object with the help of an array() function.
- NumPy array can hold only similar datatype elements, in the contiguous memory location. We can store multiple datatype values in NumPy Array
- We can perform numerical mathematical operations in NumPy Array.
- We have to define the NumPy array before using it because it not in-built.
- Storing data in NumPy Array is very compact and efficient.
To use the NumPy array try the code below, make sure you have installed NumPy module.
>>> import numpy as np >>> my_array = [['pritam', 28, 'India'], ['aaru', 23, 'USA']] >>> my_array [['pritam', 28, 'India'], ['aaru', 23, 'USA']]
Now let’s see simple mathematical operation on the NumPy array.
>>> population = [1234, 3456, 543, 6543] >>> avg_age = [32, 23, 42, 34] >>> np_population = np.array(population) >>> np_avg_age = np.array(avg_age) >>> np_total_age = np_population * np_avg_age >>> np_total_age array([ 39488, 79488, 22806, 222462])
Indexing and Slicing of a NumPy Array.
To create a NumPy array check the code in the above section I have created two np arrays np_population and np_age.
Let us discuss how to Index and slice an np array. The index in an array starts with 0. You can imagine a multidimensional array as a matrix.
#One Dimensional np array >>>import numpy as np >>>square = np.array([1,2,4,16]) >>>square #grabing the element at index 2 >>> 4 >>> square[1:3] #taking the slice of array between index 1 and 3 >>> array([2, 4]) #Two Dimensional np array >>> import numpy as np >>> numbers = np.array([ [1,2,3,4,5], [6,7,8,9,0], [5,4,3,2,1], [0,9,8,7,6] ]) >>> numbers array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], [5, 4, 3, 2, 1], [0, 9, 8, 7, 6]]) >>> numbers.shape (4, 5) #this means the array have 4 rows and 6 columns >>> numbers[1,3] # selecting based on index 9 #Slicing in 2D array >>> numbers[1:3, 2:5] array([[8, 9, 0], [3, 2, 1]])
Classes & Attributes of NumPy Array
#1 Dimension: This explains if the array is 1D, 2D, 3D array. >>> import numpy as np >>> one_D_array = np.array([1,2,3,4,5], [4,5,6,2,7]) >>> one_D_array.ndim 2 # returned 2 as it is 1D array #2 Shape: This specifies dimension and number of elements in every row. >>> one_D_array.shape (5,) #3 Size: This specifies the total number of elements of an array. >>> one_D_array.size 5 #4 Dtype: This specifies what kind of element the array stores. >>> one_D_array.dtype dtype('int64')
Basic Operations of NumPy Array
NumPy uses the indices of the elements to compute the basic operations below. I have given a few examples. The remaining processes will be the same.
I am giving a few examples below, rest you can try the syntax will be the same.
>>> import numpy as np >>> x = np.array([[1, 2, 3], [4, 5, 6]]) >>> y = np.array([ [12,23,34], [56,65,67] ]) >>> z = x+y #addition >>> z array([[13, 25, 37], [60, 70, 73]]) >>> print(z) [[13 25 37] [60 70 73]] >>> z = x*y # multiplication >>> print(z) [[ 12 46 102] [224 325 402]] >>> z = x==y #checking if equals >>> z array([[False, False, False], [False, False, False]])
Linear Algebra Using NumPy Array
NumPy provides the ability to work with universal mathematical functions like sqrt, cos, floor, exp. Below are some example of how we can utilize these functions in NumPy.
>>> import numpy as np >>> numbers = np.array([81, 49, 36, 25, 16, 4]) >>> square_root = sqrt(numbers) >>> print(square_root) [9. 7. 6. 5. 4. 2.] >>> from numpy import pi >>> np.cos(90) -0.4480736161291701 >>> np.sin(90) 0.8939966636005579 >>> np.sin(pi/2) 1.0 >>> np.floor([1.3,2,55]) array([ 1., 2., 55.]) >>> np.exp([2,3,5,6]) array([ 7.3890561 , 20.08553692, 148.4131591 , 403.42879349])
Another important feature to discuss is transpose(). By using the transpose keyword, we can interchange the row-column values of an array.
>>> a = np.array([[1,2,34,5],[5,6,7,8]]) >>> a.transpose() array([[ 1, 5], [ 2, 6], [34, 7], [ 5, 8]])
We can find the inverse of a given array and we can add its diagonal elements to get the trace of an array.
>>> arr_inverse = np.array([ [12,24],[43,56] ]) >>> np.linalg.inv(arr_inverse) array([[-0.15555556, 0.06666667], [ 0.11944444, -0.03333333]])
Now that you’ve gone through the entire article you should have gotten a good idea of basics of NumPy. You can try whatever code I have given and practice more of a NumPy. NumPy is a huge library and you can find it really interesting once you start learning more about it.
Let me know in the comments below that how do you find this article helpful. Thank you for reading. Happy learning!