NumPy

NumPy Basics Tutorial

NumPy (Numerical Python) is the foundational package for numerical computations in Python. It provides a high-performance multidimensional array object and tools for working with these arrays. In this tutorial, NumPy Basics are covered. In this tutorial 1-dimensional array are used.

Table of Contents

1. Installing NumPy

You can install NumPy using pip:

Bash
pip install numpy

2. Creating NumPy Arrays

From Lists

Python
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr)
# [1 2 3 4 5] Output

Using NumPy functions

  • Zeros: Creates an array filled with zeros
Python
zero_arr = np.zeros(5)
print(zero_arr)
# [0. 0. 0. 0. 0.]
  • Ones: Creates an array filled with ones
Python
ones_arr = np.ones(5)
print(ones_arr)
# [1. 1. 1. 1. 1.]
  • Arange: Creates an array with values in a range
Python
range_arr = np.arange(5,10)
print(range_arr)
# [5 6 7 8 9]

3. Array Attributes

  • Shape: Returns the shape of the array
Python
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr_2d.shape)
# (3,3)
  • Data Type: Returns the data type of the array
Python
print(arr.dtype)

4. Indexing and Slicing

Accessing Array Elements

Python
print(arr[0])  # First element
print(arr[-1]) # Last element

Slicing Array Elements

Python
print(arr[1:4])  # Elements from index 1 to 3

5. Array Operations

Arithmetic Operations

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

print(a + b)
print(a - b)
print(a * b)

Broadcasting

You can perform operations on arrays of different shapes. Here’s an example:

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

print(a + b)  # Adds b to each row of a

6. FAQs

  • What is the difference between a Python list and a NumPy array? While both can be used to store multiple items, NumPy arrays are more efficient for numerical operations and support broadcasting, while Python lists do not. Additionally, Python lists can store items of different data types, while NumPy arrays cannot.
  • Why use NumPy instead of Python lists for numerical computation? NumPy arrays are more memory efficient and are optimized for numerical computations, making them significantly faster than Python lists for such operations.
  • How do I change the shape of a NumPy array? You can use the reshape function to change the shape of an array. For instance, arr.reshape(2, 3) will reshape an array with 6 elements to 2 rows and 3 columns.
  • Can I perform matrix operations using NumPy? Yes, NumPy is built for numerical and matrix operations. You can perform matrix multiplication, inversion, transposition, and many other operations.

I hope this tutorial gives you a quick start with NumPy basics.

Leave a Reply

Your email address will not be published. Required fields are marked *