Python NumPy Tutorial – Learn NumPy With Examples

Python NumPy Tutorial – Learn NumPy With Examples


If you’ve been studying Python for some time, you must’ve come across NumPy. And you must’ve wondered what it is and why it is so important. NumPy stands for Numerical Python, is a library consisting of multidimensional array objects and a collection of routines for processing those arrays. Using NumPy, mathematical and logical operations on arrays can be performed. This tutorial explains the basics of NumPy. It also discusses the various array functions, types of indexing, etc. All this is explained with the help of examples for better understanding.

So, let’s get started! ?

What is a Python NumPy?

NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays.

It is the fundamental package for scientific computing with Python. It contains various features including these important ones:

  • A powerful N-dimensional array object
  • Sophisticated (broadcasting) functions
  • Tools for integrating C/C++ and Fortran code
  • Useful linear algebra, Fourier transform, and random number capabilities

Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data.
Arbitrary data-types can be defined using Numpy which allows NumPy to seamlessly and speedily integrate with a wide variety of databases.



NumPy Array: Numpy array is a powerful N-dimensional array object which is in the form of rows and columns. We can initialize numpy arrays from nested Python lists and access its elements. In order to perform these numpy operations, the next question which will come in your mind is:

How do I install NumPy?

To install Python NumPy, go to your command prompt and type “pip install numpy”. Once the installation is completed, go to your IDE (For example: Spyder) and simply import it by typing: “import numpy as np”
Moving ahead in python numpy tutorial, let us understand what exactly is a multi-dimensional numPy array.



Arrays in NumPy: A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.

We can initialize numpy arrays from nested Python lists, and access elements using square brackets:


import numpy as np
a = np.array([1, 2, 3])

# Create a rank 1 array

print(type(a))

# Prints “

print(a.shape)

# Prints “(3,)”

print(a[0], a[1], a[2])

# Prints “1 2 3”

a[0] = 5

# Change an element of the array

print(a)

# Prints “[5, 2, 3]”


b = np.array([[1,2,3],[4,5,6]]) <

# Create a rank 2 array

print(b.shape)

# Prints “(2, 3)”

print(b[0, 0], b[0, 1], b[1, 0])

# Prints “1 2 4”

Python NumPy Array v/s List

We use Python numpy array instead of a list because of the below three reasons:

  • Less Memory
  • Fast
  • Convenient

The very first reason to choose Python numpy array is that it occupies less memory as compared to list. Then, it is pretty fast in terms of execution and at the same time it is very convenient to work with numpy. So these are the major advantages that Python numpy array has over list. Don’t worry, I am going to prove the above points one by one practically. Consider the below example:


import numpy as np

import time
import sys
S= range(5000)
print(sys.getsizeof(5)*len(S))

D= np.arange(5000)
print(D.size*D.itemsize)

Outouts –

120000

40000


The above output shows that the memory allocated by list (denoted by S) is 120000 whereas the memory allocated by the numpy array is just 40000. From this, you can conclude that there is a major difference between the two and this makes python numpy array as the preferred choice over list. Next, let’s talk how Python numpy array is faster and more convenient when compared to list.


import time
import sys
import numpy as np

SIZE = 5000000

list_1= range(SIZE)
list_2= range(SIZE)
array_1= np.arange(SIZE)
array_2=np.arange(SIZE)

start= time.time()
result=[(x,y) for x,y in zip(list_1,list_2)]
print((time.time()-start)*1000)

start=time.time()
result= array_1+array_2
print((time.time()-start)*1000)
O/P – 2487.07294464
232.856988907


In the above code, we have defined two lists and two numpy arrays. Then, we have compared the time taken in order to find the sum of lists and sum of numpy arrays both. If you see the output of the above program, there is a significant change in the two values. List took 2487ms whereas the numpy array took almost 232ms. Hence, numpy array is faster than list. Now, if you noticed we had run a ‘for’ loop for a list which returns the concatenation of both the lists whereas for numpy arrays, we have just added the two array by simply printing array_1+array_2. That’s why working with numpy is much easier and convenient when compared to the lists.

Therefore, the above examples proves the point as to why you should go for Python numpy array rather than a list!

Moving forward in Python numpy tutorial, let’s focus on some of its operations.

-itemsize:

With the help of this function, you can find out the byte size of the elements of your array. Take a look at the following example:
1 import numpy as np
2 a = np.array([(1,2,3)])
3 print(a.itemsize)

The output of the above code – 4

-ndim:

The ndim function helps you find the dimension of the array. You should know that you can have one dimensional, two dimensional, as well as three-dimensional arrays. Here’s an example of this function:
1 import numpy as np
2 a = np.array([(1,2,3),(4,5,6)])
3 print(a.ndim)

The output of the above code – 2

-reshape:

With the help of the reshape operation, you can change the number of rows and columns present in an array. Suppose the one array has three columns and two rows. Through reshape, you can change them to 2 columns and three rows. See it in action through the following example:
1 import numpy as np
2 a = np.array([(8,9,10),(11,12,13)])
3 print(a)
4 a=a.reshape(3,2)
5 print(a)

Output of the above code – [[ 8 9 10] [11 12 13]] [[ 8 9] [10 11] [12 13]]

-slicing:

By using the slicing operation, you can extract a specific set of elements from the required array. In other words, you can ‘slice’ the array and get a portion of the same. Suppose you have an array and want to extract a specific element from it, you’d go about it in the following way:
1 import numpy as np
2 a=np.array([(1,2,3,4),(3,4,5,6)])
3 print(a[0,2])

The output of the above code – 3

In the example above, the index of the first array was 0, and for the second one, it was 1. So, the code says that it should print the second element of the first array (that has the index 0). Suppose you need the second element from the first and the zeroth index of the array. Then we would use the following code:
1 import numpy as np
2 a=np.array([(1,2,3,4),(3,4,5,6)])
3 print(a[0:,2])

The output of the above code– [3 5]

-dtype:

WIth the dtype function, you have the option of finding the data type of the elements of an array. It gives you the data type and the size of the required component. Take a look at the following example to see how it works:
1 import numpy as np
2 a = np.array([(1,2,3)])
3 print(a.dtype)
The output of the above code – int32

You can use the ‘shape’ and ‘size’ functions to find the shape and size of the array as well. Take a look at this example of our Python NumPy tutorial to understand these functions properly:
1 import numpy as np
2 a = np.array([(1,2,3,4,5,6)])
3 print(a.size)
4 print(a.shape)

The output of the above code – 6 (1,6)

-linspace:

With the help of the linspace operation, you can get evenly spaced numbers spread according to your mentioned interval. The linspace function has its uses, and here’s an example of how you can use it:
1 import numpy as np
2 a=np.linspace(1,3,10)
3 print(a)

Output of the above code– [ 1. 1.22222222 1.44444444 1.66666667 1.88888889 2.11111111 2.33333333 2.55555556 2.77777778 3. ]

-square root and standard deviation

Python NumPy enables you to perform various mathematical operations. And one of those operations is deriving the square root of the required array. You can also obtain the standard deviation of your NumPy array. Here’s a detailed example to help you in this regard:
1 import numpy as np
2 a=np.array([(1,2,3),(3,4,5,)])
3 print(np.sqrt(a))
4 print(np.std(a))

The output of the above code– [[ 1. 1.41421356 1.73205081]
[ 1.73205081 2. 2.23606798]]
1.29099444874

-max/min

You can find the maximum, minimum, and the sum of an array as well through the specific operations. Finding the maximum and the minimum can help you a lot in performing complex operations. Here is how you can find the maximum, minimum, and the sum of the array you have:
1 import numpy as np
2 a= np.array([1,2,3])
3 print(a.min())
4 print(a.max())
5 print(a.sum())

The output of the above code – 1 3 6

-Horizontal and vertical stacking

You might want to combine two arrays but not add them, i.e., you might just want to concatenate them. For that purpose, you can either stack them vertically or horizontally. Here is the example code for doing so:
1 import numpy as np
2 x= np.array([(1,2,3),(3,4,5)])
3 y= np.array([(1,2,3),(3,4,5)])
4 print(np.vstack((x,y)))
5 print(np.hstack((x,y)))

Output of the above code – [[1 2 3] [3 4 5] [1 2 3] [3 4 5]]
[[1 2 3 1 2 3] [3 4 5 3 4 5]]

-Addition

You can add NumPy arrays as well. Apart from addition, you can also perform subtraction, division, and multiplication of two matrices. Here’s an example of addition in Python NumPy:
1 import numpy as np
2 x= np.array([(1,2,3),(3,4,5)])
3 y= np.array([(1,2,3),(3,4,5)])
4 print(x+y)

The output of the above code – [[ 2 4 6] [ 6 8 10]]

Like we mentioned earlier, you can perform other mathematical operations on NumPy arrays as well, including subtraction and division. Here’s how:
1 import numpy as np
2 x= np.array([(1,2,3),(3,4,5)])
3 y= np.array([(1,2,3),(3,4,5)])
4 print(x-y)
5 print(x*y)
6 print(x/y)

Output of the above code– [[0 0 0] [0 0 0]]
[[ 1 4 9] [ 9 16 25]]
[[ 1. 1. 1.] [ 1. 1. 1.]]

-ravel

The ravel operation lets you convert a NumPy array into a ravel, which is a single column. Here’s an example:
1 import numpy as np
2 x= np.array([(1,2,3),(3,4,5)])
3 print(x.ravel())
The output of the code – [ 1 2 3 3 4 5]

By this, we come to the end of this Python numpy tutorial. We have covered all the basics of python numpy, so you can start practicing now. The more you practice, the more you will learn.

Got a question for us? Please mention it in the comments section of this “ Python Numpy Tutorial ” and we will get back to you as soon as possible.

To get in-depth knowledge on Python along with its various applications, you can enroll for live Python online training with 24/7 support and lifetime access.

Drop us a Query

About the author

Bhaskar

Bhaskar

The author has a keen interest in exploring the latest technologies such as AI, ML, Data Science, Cyber Security, Guidewire, Anaplan, Java, Python, Web Designing tools, Web Development Technologies, Mobile Apps, and whatnot. He bags over a decade of experience in writing technical content.

Corporate
whatsapp arrow
Loading...
// load third party scripts onload