What Is NumPy?
NumPy, which basically stands for “Numerical Python,” is a popular Python library used for numerical and mathematical calculations. It is generally useful for working with arrays, which are collections of numbers organized in a grid.
With NumPy, you can perform complex calculations much faster than with Python. This is because NumPy arrays are optimized for performance and can handle large amounts of data efficiently.
A key feature of the NumPy library is its multidimensional array data type, which means it can have more than one dimension array for tables of data. NumPy also provides many mathematical functions to perform operations like addition, subtraction, multiplication, and more on these arrays.
NumPy – Key Takeaways
- Understanding What is Numpy in Python programming language.
- Getting insights into the features of NumPy.
- Understanding the installation procedure and array creation methods in NumPy.
Features Of NumPy
NumPy is a popular Python library that makes it easy for developers and engineers to work with numbers and data. It is mainly useful in the scenario when you have a lot of calculations to do with data.
We have mentioned below, some of the unique key features of NumPy that make it a favorite tool for everyone working with numbers or data in Python.
- The most important feature of NumPy is its ability to create and manage multidimensional arrays. An array is like a list of numbers or similar data grouped together. NumPy using multidimensional arrays can hold many numbers at once, using less memory and performing faster than a regular Python list.
- NumPy makes calculations very fast. If you need to add, subtract, multiply, or divide numbers, NumPy can do it quickly, even with big sets of numbers.
- NumPy can handle different types of data, like whole numbers or decimal numbers. This means you can work with all sorts of numbers in your projects.
- NumPy works well with other Python tools like Matplotlib for making graphs and Pandas for data analysis. This makes it a great choice for many tasks in data science and machine learning.
- This is a special feature that allows you to perform operations on arrays of different shapes and sizes without writing extra code. For example, you can add a single number to every element in an array easily.
Installing NumPy
The installation of NumPy is quite simple and easy. Before moving to the installation process please ensure that Python is already installed on your PC and if it is not installed, you can install it through the official Python website.
- Now, Open the Command Prompt in your PC by typing “cmd” in the search bar and selecting it through the settings.
- After opening the Command Prompt, type the following command written below and press Enter:
pip install numpy |
The “pip” in this command stands for the package installer for Python, calling this command will help you to download and install NumPy.
- Once installed, you can cross check if NumPy is installed correctly or not, you can start a Python shell by typing `python` in the Command Prompt. Then, type the below-written command to check the NumPy installation:
import numpy
print(numpy.__version__) |
This will display the installed version of NumPy, confirming the installation.
NumPy Array Creation
Array creation in Python numPy can be done in various ways and learning these methods provide a foundational base for working with arrays in NumPy. some of the most common ways for creating an array are written below for your reference. 1. Create NumPy Array with List and Tuple
You can create a NumPy array by converting a Python list or tuple using the “np.array()” function. This method is quite easy and useful for initializing an array with specific values. The basic example of this method is written below for your better understanding of the topic:
Creating An Array with List and Tuple |
import numpy as np
# Creating an array from a list list_array = np.array([10, 20, 30, 40]) print(“Array from list:”, list_array) # Creating an array from a tuple tuple_array = np.array((1, 2, 3, 4)) print(“Array from tuple:”, tuple_array) |
Output-
Array from list: [10 20 30 40] Array from tuple: [1 2 3 4] |
2. Create An Array of Fixed Size
In this method, you can create an array of a fixed size filled with zeros, constants or randoms using `np.zeros()` and `np.full()` functions. These functions are useful when you need a placeholder array with a fixed number of elements. The basic code implementation of this array using Numpy functions is written below for better clarity:
Create An Array of Fixed Size In NumPy |
import numpy as np
# Creating a 4X4 array with all zeros c = np.zeros((4, 4)) print (“Array with all zeros:\n”, c) # Create a constant value array of complex type d = np.full((3, 3), 8, dtype = ‘complex’) print (“Array with all 8s.”:\n”, d) # Create an array with random values e = np.random.random((3, 3)) print (“A random array:\n”, e) |
Output-
Array with all zeros: [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] Array with all 8s. [[8.+0.j 8.+0.j 8.+0.j] [8.+0.j 8.+0.j 8.+0.j] [8.+0.j 8.+0.j 8.+0.j]] A random array: [[0.51232649 0.12543429 0.93746276] [0.57389056 0.83174901 0.14257313] [0.46584118 0.29798456 0.78659301]] |
3. Create Using `arange()` Function
The `np.arange()` function in the Python NumPy is used to generate an array with evenly spaced values within a given range. It’s similar to Python’s `range()` function. The basic implementation of this function is as follows:
Create Array Using `arange()` Function |
import numpy as np
# Array from 1 to 8 with step 2 arange_step_array = np.arange(1, 9, 2) print(“Array with np.arange(1, 9, 2):”, arange_step_array) |
Output-
Array with np.arange(1, 9, 2): [1 3 5 7] |
4. Reshaping Array using Reshape Method
The `reshape()` method changes the shape of an array without changing its data. This is useful when you need to adjust the dimensions of your data, for example, converting a 1D array into a 2D array. The basic code implementation of this method is written below for your better understanding
Reshaping Array using Reshape Method |
import numpy as np
# Original array original_array = np.array([1, 2, 3, 4, 5, 6]) print(“Original array:”, original_array) # Reshaped to 2×3 array reshaped_array = original_array.reshape(2, 3) print(“Reshaped array to 2×3:”, reshaped_array) |
Output-
Original array: [1 2 3 4 5 6] Reshaped array to 2×3: [[1 2 3] [4 5 6]] |
Array Indexing In NumPy
NumPy Array Indexing is a way to access and manipulate elements within a NumPy array. This is similar to how we access elements in a list in Python but offers more advanced features. Indexing allows us to retrieve or change specific elements in an array by specifying their position, known as the index. Let’s explore different ways to index arrays in NumPy, using simple examples to make it easy to understand.
- Slicing: NumPy arrays can also be sliced just like lists in Python. As we have already discussed that an array can be multi-dimensional so you need to specify a slice for each dimension of the array.
- Integer array indexing: In this method, lists are passed for indexing for each dimension. One-to-one mapping is done for corresponding elements to construct a new arbitrary array.
- Boolean array indexing: This method is generally used when we want to pick elements from the array that satisfies some condition.
Program To Demonstrate Indexing |
import numpy as np
arr = np.array([[1, -2, 5, -4], [-4, 0.5, -6, 10], [-2.6, 0, -7, 8], [3, 7, -4, -2]]) # Slicing an array temp = arr[:2, ::2] print(“Array with first 2 rows and alternate columns (0 and 2):\n”, temp) # Integer array indexing temp = arr[[0, 1, 2, 3], [3, 2, 1, 0]] print(“\nElements at indices (0, 3), (1, 2), (2, 1), (3, 0):\n”, temp) # Boolean array indexing cond = arr > 0 # cond is a boolean array temp = arr[cond] print(“\nElements greater than 0:\n”, temp) |
Output-
Array with first 2 rows and alternate columns (0 and 2): [[ 1 5] [-4 -6]] Elements at indices (0, 3), (1, 2), (2, 1), (3, 0): [-4 -6 0 3] Elements greater than 0: [ 1. 5. 0.5 10. 8. 3. 7.] |
NumPy Basic Arithmetic Operations
NumPy is a popular Python library used for plenty of numerical computation tasks, one of its main features is the ability to perform arithmetic operations on arrays. These arithmetic operations are simple, easy to perform, and efficient, making it a valuable tool for programmers and data scientists.
Let’s go through the example written below to understand some basic arithmetic operations you can perform with NumPy arrays.
Basic Arithmetic Operations |
# Python program to demonstrate basic operations on single array
import numpy as np a = np.array([1, 2, 5, 3]) # add 1 to every element print (“Adding 1 to every element:”, a+1) # subtract 3 from each element print (“Subtracting 3 from each element:”, a-3) # multiply each element by 10 print (“Multiplying each element by 10:”, a*10) # square each element print (“Squaring each element:”, a**2) # modify existing array a *= 2 print (“Doubled each element of original array:”, a) # transpose of array a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]]) print (“\nOriginal array:\n”, a) print (“Transpose of array:\n”, a.T) |
Output-
Adding 1 to every element: [2 3 6 4] Subtracting 3 from each element: [-2 -1 2 0] Multiplying each element by 10: [10 20 50 30] Squaring each element: [ 1 4 25 9] Doubled each element of original array: [ 2 4 10 6] Original array: [[1 2 3] [3 4 5] [9 6 0]] Transpose of array: [[1 3 9] [2 4 6] [3 5 0]] |
Learn Python With PW Skills
Enroll in our PW Skills Python with DSA Course to start your career as a Python Software Developer. Learn with experienced faculties from top MNCs teaching you all the in-demand tools as well as concepts of Python.
Get access to PW Lab for seamless code practice. Apart from all this, you will also get 100% placement assistance and an industry-recognized course certificate.
Hurry Up and grab your seat on this journey only at @pwskills.com.
NumPy FAQs
What are NumPy arrays, and how are they different from Python lists?
NumPy arrays are similar to Python lists but are more efficient in handling large amounts of numerical data. They provide better performance for numerical computations due to their fixed size and homogeneous nature.
What is broadcasting in NumPy?
Broadcasting is a technique used in NumPy to perform arithmetic operations on arrays of different shapes. NumPy automatically expands the smaller array to match the shape of the larger one.
What are some common functions in NumPy for mathematical operations?
Some common NumPy functions used for mathematical operations include:
np.sum() for sum
np.mean() for the average
np.median() for the median
np.std() for standard deviation