Day 33: Introduction to NumPy

Harshil Chovatiya
6 min readSep 28, 2024

Numerical Computing in Python with NumPy — A Beginner’s Guide to Arrays and More

Day 33: Introduction to NumPy | numpy, scipy, data science| Harshil Chovatiya
Day 33: Introduction to NumPy | numpy, scipy, data science| Harshil Chovatiya

Introduction

Welcome to Day 33 of our Python learning journey! Today, we delve into the world of NumPy, a powerful library for numerical computing in Python. NumPy is short for “Numerical Python” and is the foundation for many other scientific computing libraries like SciPy, Pandas, and Matplotlib. This blog will cover the basics of NumPy, including working with arrays, performing basic operations, and exploring useful functions. By the end of this blog, you will have a solid understanding of how to use NumPy for efficient numerical computations.

What is NumPy?

NumPy is an open-source library that provides support for large multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. It is highly optimized for performance, allowing for efficient numerical computations and data manipulation.

Installing NumPy

Before we start using NumPy, we need to install it. You can install NumPy using pip:

pip install numpy

Once installed, you can import NumPy in your Python script:

import numpy as np

Creating Arrays

NumPy arrays are the primary data structure of the library. They are similar to Python lists but provide additional functionality and efficiency. Let’s explore how to create NumPy arrays.

Creating a 1D Array

You can create a 1D array using the np.array function:

import numpy as np
# Creating a 1D array
arr1 = np.array([1, 2, 3, 4, 5])
print(arr1)

Output:

[1 2 3 4 5]

Creating a 2D Array

To create a 2D array (matrix), you can pass a list of lists to the np.array function:

# Creating a 2D array
arr2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr2)

Output:

[[1 2 3]
[4 5 6]
[7 8 9]]

Creating Arrays with Default Values

NumPy provides functions to create arrays with default values, such as zeros, ones, and a range of values.

# Creating an array of zeros
zeros_arr = np.zeros((3, 3))
print(zeros_arr)
# Creating an array of ones
ones_arr = np.ones((2, 4))
print(ones_arr)
# Creating an array with a range of values
range_arr = np.arange(10)
print(range_arr)

Output:

[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

[[1. 1. 1. 1.]
[1. 1. 1. 1.]]

[0 1 2 3 4 5 6 7 8 9]

Creating Arrays with Random Values

You can also create arrays with random values using np.random functions.

Creating Arrays with Random Values | numpy | Harshil Chovatiya
Creating Arrays with Random Values | numpy | Harshil Chovatiya

Output:

[[0.7547214  0.45559388 0.48690803]
[0.68506744 0.94763381 0.60285342]
[0.71635325 0.18925373 0.93167656]]

[[5 8 3]
[7 7 8]
[9 5 4]]

Basic Operations with NumPy Arrays

NumPy arrays support a wide range of operations that can be performed element-wise or across entire arrays. Let’s explore some basic operations.

Arithmetic Operations

You can perform arithmetic operations on NumPy arrays just like you would with scalar values.

# Creating arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Element-wise addition
print(a + b)
# Element-wise subtraction
print(a - b)
# Element-wise multiplication
print(a * b)
# Element-wise division
print(a / b)

Output:

[5 7 9]
[-3 -3 -3]
[ 4 10 18]
[0.25 0.4 0.5 ]

Mathematical Functions

NumPy provides a variety of mathematical functions that operate element-wise on arrays.

Mathematical Functions in python |numpy | Harshil Chovatiya
Mathematical Functions in python |numpy | Harshil Chovatiya

Output:

[0.         0.5        0.70710678 0.8660254  1.        ]
[ 1.000000e+00 8.660254e-01 7.071068e-01 5.000000e-01 6.123234e-17]
[1.00000000e+00 1.06864746e+13 3.49342711e+19 1.14200739e+26 1.22040329e+39]
[-inf 3.40119738 3.80666249 4.09434456 4.49980967]

Aggregation Functions

Aggregation functions compute a single value from an array, such as the sum, mean, or maximum value.

# Creating an array
arr = np.array([1, 2, 3, 4, 5])
# Sum of elements
print(np.sum(arr))
# Mean of elements
print(np.mean(arr))
# Maximum and minimum values
print(np.max(arr))
print(np.min(arr))

Output:

15
3.0
5
1

Array Indexing and Slicing

NumPy arrays support advanced indexing and slicing techniques, allowing you to access and manipulate array elements efficiently.

Indexing

You can access individual elements of a NumPy array using square brackets and indices.

# Creating a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Accessing elements
print(arr[0, 0]) # First element of the first row
print(arr[1, 2]) # Third element of the second row

Output:

1
6

Slicing

Slicing allows you to extract subarrays from a NumPy array using a range of indices.

# Creating a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Slicing rows and columns
print(arr[0:2, 1:3]) # Extracts a subarray from the first two rows and second and third columns

Output:

[[2 3]
[5 6]]

Reshaping and Resizing Arrays

NumPy provides functions to reshape and resize arrays without changing their data.

Reshaping

The reshape function changes the shape of an array while keeping its data intact.

# Creating a 1D array
arr = np.arange(6)
# Reshaping into a 2x3 array
reshaped_arr = arr.reshape((2, 3))
print(reshaped_arr)

Output:

[[0 1 2]
[3 4 5]]

Resizing

The resize function changes the shape and size of an array. If the new size is larger, the array is filled with repeated copies of its data.

# Creating a 1D array
arr = np.array([1, 2, 3, 4, 5, 6])
# Resizing into a 3x3 array
resized_arr = np.resize(arr, (3, 3))
print(resized_arr)

Output:

[[1 2 3]
[4 5 6]
[1 2 3]]

Useful NumPy Functions

NumPy offers a wide range of useful functions for numerical computations. Let’s explore some of them.

linspace and logspace

The linspace and logspace functions generate arrays with evenly spaced values over a specified range.

# Creating an array with 10 evenly spaced values between 0 and 1
linspace_arr = np.linspace(0, 1, 10)
print(linspace_arr)
# Creating an array with 10 logarithmically spaced values between 10^0 and 10^2
logspace_arr = np.logspace(0, 2, 10)
print(logspace_arr)

Output:

[0.  0.11111111  0.22222222  0.33333333  0.44444444  0.55555556 0.66666667  0.77777778  0.88888889  1.        ]
[ 1. 1.66810054 2.7825594 4.64158883 7.74263683 12.91549665 21.5443469 35.93813664 59.94842503 100. ]

Meshgrid

The meshgrid function creates coordinate matrices from coordinate vectors, which is useful for evaluating functions over a grid.

# Creating coordinate vectors
x = np.linspace(-5, 5, 5)
y = np.linspace(-5, 5, 5)
# Creating coordinate matrices
xx, yy = np.meshgrid(x, y)
print(xx)
print(yy)
# Evaluating a function over the grid
z = np.sin(np.sqrt(xx**2 + yy**2))
print(z)

Output:

[[-5.  -2.5  0.   2.5  5. ]
[-5. -2.5 0. 2.5 5. ]
[-5. -2.5 0. 2.5 5. ]
[-5. -2.5 0. 2.5 5. ]
[-5. -2.5 0. 2.5 5. ]]
[[-5. -5. -5. -5. -5. ]
[-2.5 -2.5 -2.5 -2.5 -2.5]
[ 0. 0. 0. 0. 0. ]
[ 2.5 2.5 2.5 2.5 2.5]
[ 5. 5. 5. 5. 5. ]]
[[-0.70886129 -0.88627755 0. 0.88627755 0.70886129]
[-0.88627755 -0.98776595 0. 0.98776595 0.88627755]
[ 0. 0. 0. 0. 0. ]
[ 0.88627755 0.98776595 0. 0.98776595 0.88627755]
[ 0.70886129 0.88627755 0. 0.88627755 0.70886129]]

Broadcasting

Broadcasting is a powerful mechanism that allows NumPy to perform operations on arrays of different shapes.

# Creating arrays
a = np.array([1, 2, 3])
b = np.array([[1], [2], [3]])
# Broadcasting the addition operation
result = a + b
print(result)

Output:

[[2 3 4]
[3 4 5]
[4 5 6]]

Performance Comparison

NumPy arrays are optimized for performance and can significantly speed up numerical computations compared to pure Python. Let’s compare the performance of summing elements in a list and a NumPy array.

optimized for performance with numpy | Harshil Chovatiya
optimized for performance with numpy | Harshil Chovatiya

Output:

Sum of list: 499999500000, Time taken: 0.08081912994384766
Sum of array: 499999500000, Time taken: 0.007857084274291992

Conclusion

In this blog, we’ve explored the basics of NumPy, a powerful library for numerical computing in Python. We’ve covered how to create and manipulate arrays, perform basic operations, use advanced indexing and slicing techniques, and leverage useful functions provided by NumPy. Additionally, we’ve discussed the performance benefits of using NumPy for numerical computations.

NumPy is a foundational library for scientific computing in Python, and mastering it will open up numerous possibilities for data analysis, machine learning, and more. As you continue your Python learning journey, you’ll find NumPy to be an indispensable tool for efficient and effective numerical computations.

Happy coding, and see you on Day 34!

by Harshil Chovatiya

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Harshil Chovatiya
Harshil Chovatiya

Written by Harshil Chovatiya

Passionate Python and Flutter developer creating dynamic apps and tools. Focused on seamless user experiences and backend efficiency.

No responses yet

Write a response