5. Numpy#

5.1. Introduction#

The numpy package is essential for handling arrays and matrices in Python, making it invaluable for processing and visualizing scientific data. It offers a wide range of functions for various operations, including mathematics, logic, linear algebra, Fourier transforms, and more. In this section, you will explore commonly used numpy functions to work with multidimensional arrays.

Here is how you can import the numpy package in python:

import numpy as np

Here is a table of what you should know after this topic:

Function

Definition

Example

Array Type

np.array()

Creates an array from a given sequence or iterable object.

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

One-Dimensional

np.zeros()

Creates an array filled with zeros.

arr = np.zeros((3, 4))

Two-Dimensional

np.asarray()

Converts a given input to an array.

arr = np.asarray([1, 2, 3, 4, 5])

One-Dimensional

np.shape()

Returns the shape of an array (number of rows and columns).

shape = np.shape(arr)

-

np.min()

Returns the minimum value in an array.

minimum = np.min(arr)

-

np.max()

Returns the maximum value in an array.

maximum = np.max(arr)

-

np.mean()

Computes the mean (average) value of an array.

mean = np.mean(arr)

-

np.sort()

Sorts the elements of an array in ascending order.

sorted_arr = np.sort(arr)

-

np.linspace()

Returns evenly spaced numbers over a specified interval.

arr = np.linspace(0, 10, 5)

One-Dimensional

np.arange()

Returns evenly spaced values within a given interval.

arr = np.arange(0, 10, 2)

One-Dimensional

np.argmax()

Returns the indices of the maximum values along a specified axis.

index = np.argmax(arr)

-

np.argmin()

Returns the indices of the minimum values along a specified axis.

index = np.argmin(arr)

-

np.where()

Returns the indices where a given condition is true.

indices = np.where(arr > 3)

-

np.astype()

Changes the data type of an array.

arr = arr.astype(np.float64)

-

np.dot()

Computes the dot product of two arrays.

result = np.dot(arr1, arr2)

-

np.transpose()

Transposes the rows and columns of an array.

arr_transposed = np.transpose(arr)

-

np.loadtxt()

Loads data from a text file into an array.

arr = np.loadtxt('data.txt')

Two-Dimensional

np.sum()

Computes the sum of array elements.

sum = np.sum(arr)

-

np.cos()

Computes the cosine of each element in the array.

cos_arr = np.cos(arr)

-

np.sin()

Computes the sine of each element in the array.

sin_arr = np.sin(arr)

-

np.sqrt()

Computes the square root of each element in the array.

sqrt_arr = np.sqrt(arr)

-

Conditions within arrays#

You can also use conditions to check for values within an array. For example:

arr = np.array([-1, 0, 1, 2, 3])

filtered_arr = arr[arr > 0]

print("Original Array:", arr)
print("Filtered Array (Positive Elements):", filtered_arr)
Original Array: [-1  0  1  2  3]
Filtered Array (Positive Elements): [1 2 3]

Numpy provides a variety of functions for linear algebra operations. These functions are used to perform operations on matrices and solve systems of linear equations. Here are a few commonly used functions from np.linalg:

Function

Description

np.linalg.inv

Computes the inverse of a square matrix.

np.linalg.det

Calculates the determinant of a square matrix.

np.linalg.eig

Computes the eigenvalues and eigenvectors of a square matrix.

np.linalg.solve

Solves a system of linear equations.

Let’s focus on the np.linalg.solve function, which is used to solve a system of linear equations. It takes two arguments: the coefficient matrix A and the dependent variable vector b. The function solves the equation Ax = b and returns the solution vector x. To illustrate this, here is an example:

import numpy as np

# Coefficient matrix
A = np.array([[2, 3], [4, 1]])

# Dependent variable vector
b = np.array([8, 10])

# Solve the equation Ax = b
x = np.linalg.solve(A, b)

print(x)
[2.2 1.2]

The @ operator in Python is used for matrix multiplication when working with Numpy arrays. Here’s an example that demonstrates the usage of the @ operator for matrix multiplication:

import numpy as np

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

matrix2 = np.array([[5, 6],
                    [7, 8]])

result = matrix1 @ matrix2

print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
print("\nResult of Matrix Multiplication:")
print(result)
Matrix 1:
[[1 2]
 [3 4]]

Matrix 2:
[[5 6]
 [7 8]]

Result of Matrix Multiplication:
[[19 22]
 [43 50]]