How to Learn NumPy: A Step-by-Step Guide for Beginners

Usama waqasUsama waqas
4 min read

Let's simplify the explanation of NumPy, starting from the very basics (Zero) and moving toward advanced concepts step by step. We will make it as straightforward as possible while covering all the important features.


Step 1: Installing NumPy

Before using NumPy, you need to install it:

pip install numpy

Step 2: Importing NumPy

Always import NumPy before using it:

import numpy as np

Step 3: Creating Arrays

Arrays are the main way to store data in NumPy.

1D Array:

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

2D Array (like a table):

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

Special Arrays (zeros, ones):

# Array of zeros
zeros = np.zeros(5)  # Output: [0. 0. 0. 0. 0.]

# Array of ones
ones = np.ones((2, 3))  # Output: [[1. 1. 1.] [1. 1. 1.]]

Step 4: Array Information

To get information about an array:

  • shape: Tells the dimensions (rows and columns).

  • ndim: Number of dimensions (1D, 2D, etc.).

  • size: Total number of elements.

  • dtype: Type of the data (int, float, etc.).

print(a.shape)  # Output: (4,) -> 1 row, 4 elements
print(b.shape)  # Output: (2, 2) -> 2 rows, 2 columns

print(a.ndim)   # Output: 1 -> 1D array
print(b.ndim)   # Output: 2 -> 2D array

print(a.size)   # Output: 4 -> 4 elements
print(a.dtype)  # Output: int64 -> Data type is integer

Step 5: Accessing and Changing Data

Indexing (Accessing Elements):

# 1D Array
print(a[0])  # Output: 1 -> First element

# 2D Array
print(b[1, 1])  # Output: 4 -> Row 1, Column 1 (Note: Index starts from 0)

Slicing (Selecting a range of elements):

# 1D slicing
print(a[1:3])  # Output: [2 3] -> Elements from index 1 to 2

# 2D slicing
print(b[:, 1])  # Output: [2 4] -> All rows, second column

Step 6: Reshaping Arrays

You can change the shape of an array without changing its data.

c = np.array([1, 2, 3, 4, 5, 6])
reshaped_c = c.reshape(2, 3)
print(reshaped_c)
# Output:
# [[1 2 3]
#  [4 5 6]]

Step 7: Basic Operations

You can easily do mathematical operations on arrays:

Element-wise Operations:

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

# Addition
print(a + b)  # Output: [5 7 9]

# Multiplication
print(a * b)  # Output: [ 4 10 18]

Broadcasting:

If arrays have different shapes, NumPy automatically adjusts them to work together.

a = np.array([[1, 2], [3, 4]])
b = np.array([10, 20])

print(a + b)
# Output:
# [[11 22]
#  [13 24]]

Step 8: Aggregate Functions

NumPy has built-in functions to do common calculations like sum, mean (average), etc.

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

# Sum of all elements
print(np.sum(a))  # Output: 10

# Mean (average)
print(np.mean(a))  # Output: 2.5

Step 9: Generating Random Numbers

You can generate random numbers with NumPy, which is useful in simulations.

# Random numbers between 0 and 1
rand_nums = np.random.rand(3)
print(rand_nums)

# Random integers between 0 and 10
rand_ints = np.random.randint(0, 10, 5)
print(rand_ints)

Step 10: Linear Algebra

NumPy can handle matrix operations, which are essential in math and machine learning.

Matrix Multiplication:

A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

result = np.dot(A, B)  # Matrix multiplication
print(result)
# Output:
# [[19 22]
#  [43 50]]

Step 11: Saving and Loading Arrays

You can save an array to a file and load it later.

Saving:

a = np.array([1, 2, 3])
np.save('my_array.npy', a)

Loading:

loaded_a = np.load('my_array.npy')
print(loaded_a)  # Output: [1 2 3]

Step 12: Handling Missing Data

NumPy can handle missing values, often represented by NaN (Not a Number).

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

# Check for NaN values
print(np.isnan(a))  # Output: [False False  True False]

# Remove NaN values
cleaned_a = a[~np.isnan(a)]
print(cleaned_a)  # Output: [1. 2. 4.]

Summary:

Starting with Basic Concepts:

  1. Install and import NumPy.

  2. Create 1D, 2D arrays.

  3. Get information about the arrays (shape, size, etc.).

  4. Access and modify elements using indexing and slicing.

  5. Reshape arrays.

Moving to Operations and Advanced Concepts:

  1. Perform element-wise operations and broadcasting.

  2. Use functions to sum, average, etc.

  3. Generate random numbers and handle missing data.

  4. Work with linear algebra and matrix operations.

  5. Save and load arrays from files.

This guide should help you cover everything from basic to advanced NumPy features in a simple and easy-to-follow manner!

4o

0
Subscribe to my newsletter

Read articles from Usama waqas directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Usama waqas
Usama waqas

As a MERN stack developer with six months of experience, I have honed my skills in building dynamic web applications using MongoDB, Express.js, React.js, and Node.js. In addition to my development work, I am actively involved in AI research, further expanding my technical expertise and contributing to innovative solutions.