Programs

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

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

 Executive Post Graduate Programme in Data Science from IIITB Professional Certificate Program in Data Science for Business Decision Making Master of Science in Data Science from University of Arizona Advanced Certificate Programme in Data Science from IIITB Professional Certificate Program in Data Science and Business Analytics from University of Maryland 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

 SL. No Top Data Science Skills to Learn 1 Data Analysis Online Courses Inferential Statistics Online Courses 2 Hypothesis Testing Online Courses Logistic Regression Online Courses 3 Linear Regression Courses Linear Algebra for Analysis Online Courses

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

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

 Data Science Career Path: A Comprehensive Career Guide Data Science Career Growth: The Future of Work is here Why is Data Science Important? 8 Ways Data Science Brings Value to the Business Relevance of Data Science for Managers The Ultimate Data Science Cheat Sheet Every Data Scientists Should Have Top 6 Reasons Why You Should Become a Data Scientist A Day in the Life of Data Scientist: What do they do? Myth Busted: Data Science doesnâ€™t need Coding Business Intelligence vs Data Science: What are the differences?

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.

## What 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.

## What 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.

## Is 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.