Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconPython NumPy Tutorial: Learn Python Numpy With Examples

Python NumPy Tutorial: Learn Python Numpy With Examples

Last updated:
21st Jun, 2023
Views
Read Time
11 Mins
share image icon
In this article
Chevron in toc
View All
Python NumPy Tutorial: Learn Python 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. In this Python Numpy tutorial, you’ll get to learn about the same. You’ll get to understand NumPy as well as NumPy arrays and their functions.

Having mastery over Python is necessary for modern-day programmers. And this Python NumPy tutorial will help you in understanding Python better. It’s quite detailed, so we recommend adding this page to your bookmarks for future reference. 

Learn data science online courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

What is Python NumPy?

NumPy stands for ‘Numerical Python.’ As you would’ve guessed, it focuses on numerical operations and computing. Numpy is a Python package and is the main library for scientific computations. It has n-dimensional array objects and tools to integrate other dominant languages such as C. You can use the NumPy array as an enormous multi-dimensional container for data. 

Advantages of selecting Numpy in Python tutorial

One advantage of a NumPy tutorial is that it empowers learners to efficiently process and analyze large datasets. Choosing NumPy in Python tutorial has the following benefits:

  1. Fewer loops: NumPy aids in the reduction of loops and prevents you from becoming confused by iteration indices Without loops, your code will be more readable and resemble the equations you’re trying to solve.
  2. Effective numeric computation: Compared to standard Python lists, NumPy operates on arrays more quickly and is optimised for numerical computations.
  3. Better quality: NumPy is kept quick, user-friendly, and bug-free by hundreds of volunteers. NumPy employs C-coded algorithms that finish in nanoseconds as opposed to seconds.
  4. Rapid Integration: SciPy, pandas, and Matplotlib are just a few of the well-known Python libraries that NumPy smoothly interacts with. Users may combine the benefits of many libraries for thorough data analysis processes thanks to this compatibility.
  5. Broad Functionality: Numerous mathematical and statistical functions that are crucial for scientific computing and data analysis are provided by NumPy.

What is a NumPy Array?

The NumPy array is a fantastic n-dimensional array object. It has rows and columns, and you can use it to access the elements of a Python list. There are many operations you can perform on a NumPy array. We’ve discussed them later in the article, but before that, you must understand how to install NumPy in your system. Without installing it, you wouldn’t be able to use it. 

How to install NumPy?

You’ll have to go to the command prompt and enter ‘pip install numpy’ to install Python NumPy. After the installation is complete, you’ll have to go to the IDE and import numpy through ‘import numpy as np’. And that’s how you install Numpy on your system.

Ways to create arrays in NumPy

In the NumPy tutorial, arrays may be created in a variety of ways.

  • The array method, for instance, allows you to turn a conventional Python list or tuple into an array. The type of the items in the sequences is used to determine the type of the resultant array.
  • Frequently, an array’s items are initially unknown, but its size is known. As a result, NumPy provides a number of routines for building arrays using initial placeholder data. These reduce the need for costly array-growing operations. np.zeros, np.ones, np.full, np.empty, etc. are a few examples.
  • NumPy has a method similar to the range for creating sequences of integers, except it outputs arrays rather than lists.

You can create arrays in NumPy easily through the following code:

1 import numpy as np

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

3 print(a) 

The output of the above code – [1 2 3]

The code above would give you a one-dimensional array. If you want to create a multidimensional array, you’d have to write something similar to the example present below:

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

2 print(a)

The output of the above code – [[ 1 2 3]

[4 5 6]]

Read more: 25 Exciting Python Project Ideas & Topics for Beginners

Ways to do array indexing in NumPy

Understanding the fundamentals of array indexing is crucial for analysing and working with the array object. Numerous array indexing options are provided by NumPy.

  • Slicing: NumPy arrays can be sliced in the same way as lists in Python can. Given that arrays might have many dimensions, you must define a slice for each dimension.
  • Indexing an integer array: In this procedure, lists are supplied for each dimension’s indexing. To create a new arbitrary array, relevant items are mapped one to one.
  • Indexing a Boolean array: When selecting elements from an array that meets a criterion, we utilise this approach.

What distinguishes a Python list from a NumPy array?

In a Python NumPy tutorial, it’s essential to understand the distinctions between Python lists and NumPy arrays. With NumPy, you have a wide range of tools for quickly and effectively creating arrays and manipulating data. A Python list can include a variety of data types, while NumPy arrays can only contain elements of the same data type. The proposed mathematical procedures would be exceedingly inefficient if the arrays were not uniform.

NumPy arrays offer vectorized operations and are optimised for numerical calculations. Using vectorized operations, it is possible to do element-wise calculations on whole arrays without using explicit loops. As a result, NumPy arrays perform numerical operations much quicker than Python lists, greatly increasing computational efficiency.

Operations in NumPy

Python NumPy has many operations. They all perform specific functions. Here are those functions with a brief description:

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

Explore our Popular Data Science Courses

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]

Also read: Python Developer Salary in India

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

Top Data Science Skills to Learn to upskill

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]]

Read more: Operators in Python: A Beginner’s Guide to Arithmetic

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]

Read our popular Data Science Articles

upGrad’s Exclusive Data Science Webinar for you –

Watch our Webinar on How to Build Digital & Data Mindset?

Check out all trending Python tutorial concepts in 2024.

Conclusion

We’re sure that you have found this Python NumPy tutorial quite informative. By now, you’d have understood what Python NumPy is and what its functions are. If you have any more questions about this topic, feel free to let us know. 

If you are curious to learn about data science, check out IIIT-B & upGrad’s Executive PG Program in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Frequently Asked Questions (FAQs)

1What is the use of NumPy in Python?

NumPy is a widely used library for working with arrays in Python. There are certain functions in NumPy that can also allow you to work in the domain of matrices, Fourier transform, and linear algebra.

Lists are used in Python for serving the purpose of an array. The only downside here is that they are pretty slow to process. NumPy has the ability to provide an array object, which is found to be 50x faster as compared to the traditional Python lists. There are various supporting functions provided with the array object in NumPy in order to make its working much simpler and easier. Whenever it comes to speed and resources in data science, arrays are considered, and that’s when NumPy comes into play.

2What is the best way to learn NumPy?

When it comes to fundamental packages for functioning in Python, NumPy is included in the list. NumPy is a well-known library in Python because of several dynamic features like high-level syntax, the flexibility of Python with the speed of the compiled code, numerical computing tools, and more.

When you are beginning to learn NumPy, it is best to go through some online tutorials and read the NumPy Official Document. This will help to lay down the foundational knowledge before you move towards the advanced concepts. Later on, you can use other resources like YouTube tutorials or even take up a course to get in-depth knowledge about working with NumPy in Python.

3Is NumPy array faster or a list?

NumPy array is known to be a faster alternative to the traditional Python lists. No matter what operation you wish to perform on the data, you will find that the NumPy array is much more accurate than a list.

As the size of the array increases, the speed of NumPy gets 30x faster as compared to the Python lists. So, even if you perform a simple delete operation, you'll notice that NumPy arrays are fast. As the NumPy arrays are densely packed because of its homogeneous type, it also tends to clear memory faster.

Explore Free Courses

Suggested Blogs

Data Mining Techniques & Tools: Types of Data, Methods, Applications [With Examples]
101481
Why data mining techniques are important like never before? Businesses these days are collecting data at a very striking rate. The sources of this eno
Read More

by Rohit Sharma

07 Jul 2024

An Overview of Association Rule Mining & its Applications
142252
Association Rule Mining in data mining, as the name suggests, involves discovering relationships between seemingly independent relational databases or
Read More

by Abhinav Rai

07 Jul 2024

What is Decision Tree in Data Mining? Types, Real World Examples & Applications
16859
Introduction to Data Mining In its raw form, data requires efficient processing to transform into valuable information. Predicting outcomes hinges on
Read More

by Rohit Sharma

04 Jul 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
82607
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

04 Jul 2024

Most Common Binary Tree Interview Questions & Answers [For Freshers & Experienced]
10068
Introduction Data structures are one of the most fundamental concepts in object-oriented programming. To explain it simply, a data structure is a par
Read More

by Rohit Sharma

03 Jul 2024

Data Science Vs Data Analytics: Difference Between Data Science and Data Analytics
70152
Summary: In this article, you will learn, Difference between Data Science and Data Analytics Job roles Skills Career perspectives Which one is right
Read More

by Rohit Sharma

02 Jul 2024

Graphs in Data Structure: Types, Storing & Traversal
51859
In my experience with Data Science, I’ve found that choosing the right data structure is crucial for organizing information effectively. Graphs
Read More

by Rohit Sharma

01 Jul 2024

Python Banking Project [With Source Code] in 2024
14920
The banking sector has many applications for programming and IT solutions. If you’re interested in working on a project for the banking sector,
Read More

by Rohit Sharma

25 Jun 2024

Linear Search vs Binary Search: Difference Between Linear Search & Binary Search
66264
In my journey through data structures, I’ve navigated the nuances of linear search vs binary search in data structure, especially when dealing w
Read More

by Rohit Sharma

23 Jun 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon