NumPy : Basic Operations and Arrays
Welcome back! In this tutorial, we’ll dive into NumPy, a powerful library for numerical computing in Python. NumPy makes it easy to work with arrays and perform a variety of mathematical operations. Let’s get started!
What is NumPy?
NumPy stands for Numerical Python. It provides support for arrays, which are collections of elements (usually numbers) that can be indexed. Arrays are similar to lists in Python, but they come with additional functionality for performing mathematical operations efficiently.
Step 1: Importing NumPy
Before we start using NumPy, we need to import it into our notebook. We’ll use the alias np
to make it easier to reference.
import numpy as np
Step 2: Creating Arrays
Let’s create our first NumPy array. There are several ways to create arrays, but we’ll start with the most basic one: using a list.
# Creating an array from a list
my_list = [1, 2, 3, 4, 5]
my_array = np.array(my_list)
print(my_array)
This code creates a NumPy array from a list of numbers and prints it.
Step 3: Basic Array Operations
Now that we have an array, let’s perform some basic operations.
1. Array Addition:
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
sum_array = array1 + array2
print(sum_array)
2. Array Multiplication:
product_array = array1 * array2
print(product_array)
3. Scalar Operations:
scalar_mult = array1 * 2
print(scalar_mult)
Step 4: Array Indexing and Slicing
Indexing and slicing allow us to access and modify specific elements in an array.
1. Accessing Elements:
# Accessing the first element
first_element = my_array[0]
print(first_element)
2. Slicing Arrays:
# Slicing the first three elements
slice_array = my_array[0:3]
print(slice_array)
Step 5: Array Properties
NumPy arrays have several important properties, such as shape, size, and data type.
1. Shape:
print(my_array.shape)
2. Size:
print(my_array.size)
3. Data Type:
print(my_array.dtype)
Step 6: Creating Special Arrays
NumPy provides functions to create special arrays, like arrays of zeros, ones, and random numbers.
1. Array of Zeros:
zeros_array = np.zeros(5)
print(zeros_array)
2. Array of Ones:
ones_array = np.ones(5)
print(ones_array)
3. Random Array:
random_array = np.random.random(5)
print(random_array)
Conclusion
In this tutorial, we’ve introduced you to NumPy and covered the basics of creating and manipulating arrays. We’ve explored array operations, indexing, slicing, and some special array creation functions. NumPy is a powerful tool that will help you perform numerical computations efficiently.
In the next tutorial, we’ll explore Pandas and learn how to work with Series and DataFrames, which are essential for data analysis. Stay tuned and keep practicing!