NumPy Basic Operations

FARSHAD K
5 min readFeb 16, 2024

NumPy, which stands for Numerical Python, is a powerful library for numerical computations in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these elements. The library is a cornerstone in the field of scientific computing.

1. Creating Arrays:

numpy.array()

The array function is used to create arrays from existing data or create arrays filled with specific values.

import numpy as np
arr = np.array([1, 2, 3])

numpy.zeros()

Creates an array filled with zeros.

zeros_arr = np.zeros((2, 3))

numpy.ones()

Creates an array filled with ones.

ones_arr = np.ones((3, 2))

numpy.arange()

Generates an array with evenly spaced values within a specified range.

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

numpy.linspace()

Generates an array with a specified number of evenly spaced values over a specified range.

linspace_arr = np.linspace(0, 1, 5)

numpy.eye()

Creates a 2D identity matrix with ones on the diagonal and zeros elsewhere.

identity_mat = np.eye(3)

2. Array Operations:

Element-wise Operations:

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Addition
sum_arr = a + b
# Subtraction
diff_arr = a - b
# Multiplication
prod_arr = a * b
# Division
div_arr = a / b
# Exponentiation
exp_arr = a ** 2

Matrix Operations:

mat_a = np.array([[1, 2], [3, 4]])
mat_b = np.array([[5, 6], [7, 8]])
# Matrix Multiplication
mat_mul = np.dot(mat_a, mat_b)
# Transpose
mat_transpose = mat_a.T
# Determinant
mat_det = np.linalg.det(mat_a)
# Inverse
mat_inv = np.linalg.inv(mat_a)

3. Array Manipulation:

numpy.reshape()

Reshapes an array to a specified shape.

reshaped_arr = np.reshape(range_arr, (2, 3))

numpy.concatenate()

Concatenates two or more arrays along a specified axis.

concat_arr = np.concatenate((a, b))

numpy.split()

Splits an array into multiple sub-arrays.

split_arr = np.split(concat_arr, 2)

numpy.flatten()

Flattens a multi-dimensional array into a 1D array.

flattened_arr = mat_a.flatten()

4. Mathematical Functions:

numpy.sum()

Calculates the sum of array elements.

total_sum = np.sum(a)

numpy.mean()

Calculates the mean of array elements.

average = np.mean(a)

numpy.sqrt()

Calculates the square root of array elements.

sqrt_arr = np.sqrt(a)

numpy.sin()

Calculates the sine of array elements.

sin_arr = np.sin(a)

5. Statistical Functions:

numpy.min()

Finds the minimum value in an array.

min_val = np.min(a)

numpy.max()

Finds the maximum value in an array.

max_val = np.max(a)

numpy.std()

Calculates the standard deviation of array elements.

std_dev = np.std(a)

numpy.mean()

Calculates the mean of array elements.

average = np.mean(a)

6. Linear Algebra:

numpy.dot()

Performs dot product of two arrays.

dot_product = np.dot(a, b)

numpy.cross()

Computes the cross product of two arrays.

cross_product = np.cross(a, b)

numpy.linalg.norm()

Calculates the norm of a vector or matrix.

vector_norm = np.linalg.norm(arr_a)

numpy.linalg.eig()

Computes the eigenvalues and right eigenvectors of a square array.

eigenvalues, eigenvectors = np.linalg.eig(mat_a)

numpy.linalg.solve()

Solves a linear matrix equation.

linear_eq_result = np.linalg.solve(mat_a, arr_c)

7. Random:

numpy.random.rand()

Generates random values in a given shape from a uniform distribution over [0, 1).

random_values = np.random.rand(2, 3)

numpy.random.randn()

Generates random values in a given shape from a standard normal distribution.

random_normal_values = np.random.randn(2, 3)

numpy.random.randint()

Generates random integers in a specified range.

random_integers = np.random.randint(1, 10, size=(3, 3))

8. Indexing and Slicing:

numpy.ndarray indexing

NumPy allows for indexing and slicing arrays, similar to Python lists.

arr = np.array([0, 1, 2, 3, 4, 5])
# Accessing elements
first_element = arr[0]
# Slicing
slice_of_arr = arr[2:5]
# Assigning values
arr[1] = 10

9. Boolean Indexing:

NumPy supports boolean indexing, allowing you to filter elements based on conditions.

bool_arr = arr > 2
filtered_arr = arr[bool_arr]

10. Array Comparison:

NumPy provides functions for element-wise array comparison.

arr_a = np.array([1, 2, 3])
arr_b = np.array([1, 2, 4])
# Element-wise comparison
elementwise_comparison = arr_a == arr_b
# Array-wise comparison
arraywise_comparison = np.array_equal(arr_a, arr_b)

11. Sorting:

NumPy arrays can be sorted using the sort method.

unsorted_arr = np.array([3, 1, 4, 1, 5, 9, 2, 6])
sorted_arr = np.sort(unsorted_arr)

12. Unique Elements:

Finding unique elements in an array.

unique_elements = np.unique(unsorted_arr)

13. Stacking and Splitting:

numpy.vstack() and numpy.hstack()

Stacking arrays vertically and horizontally.

arr_c = np.array([7, 8, 9])
vertical_stack = np.vstack((arr_a, arr_c))
horizontal_stack = np.hstack((arr_a, arr_c))

numpy.split()

Splitting arrays at specified positions.

split_arr = np.split(unsorted_arr, [2, 5])

14. Array Iteration:

NumPy arrays can be iterated using loops.

for num in arr:
print(num)

15. Save and Load:

numpy.save() and numpy.load()

Saving and loading arrays to and from disk.

np.save('saved_array.npy', arr)
loaded_arr = np.load('saved_array.npy')

16. Broadcasting:

NumPy supports broadcasting, allowing operations on arrays of different shapes and sizes.

broadcasted_sum = arr_a + 5

17. Interpolation:

NumPy can perform interpolation using numpy.interp().

x = np.linspace(0, 10, 10)
y = np.sin(x)
x_new = np.linspace(0, 10, 30)
y_new = np.interp(x_new, x, y)

18. FFT (Fast Fourier Transform):

NumPy supports Fourier transforms.

signal = np.array([1, 2, 1, -1, 1.5])
fft_result = np.fft.fft(signal)

19. Histograms:

NumPy provides functions for creating histograms.

hist_values, bin_edges = np.histogram(arr_a, bins=3)

20. Datetime Operations:

NumPy can handle datetime objects.

date_array = np.array(['2022-01-01', '2022-01-02'], dtype='datetime64')
date_diff = np.diff(date_array)

21. Exponential and Logarithmic Functions:

numpy.exp()

Computes the element-wise exponential of an array.

exp_arr = np.exp(arr_a)

numpy.log()

Computes the element-wise natural logarithm of an array.

log_arr = np.log(arr_a)

22. Trigonometric Functions:

numpy.cos(), numpy.tan(), etc.

Computes the element-wise cosine, tangent, etc.

cos_arr = np.cos(arr_a)
tan_arr = np.tan(arr_a)

23. Hyperbolic Functions:

numpy.sinh(), numpy.cosh(), etc.

Computes the hyperbolic sine, cosine, etc.

sinh_arr = np.sinh(arr_a)
cosh_arr = np.cosh(arr_a)

24. Rounding Functions:

numpy.round()

Rounds array elements to the nearest integer.

rounded_arr = np.round(arr_a)

numpy.floor(), numpy.ceil()

Rounds down and up, respectively.

floor_arr = np.floor(arr_a)
ceil_arr = np.ceil(arr_a)

25. Binary Operations:

numpy.bitwise_and(), numpy.bitwise_or(), etc.

Bitwise operations on integer arrays.

bitwise_and_result = np.bitwise_and(arr_a, arr_b)
bitwise_or_result = np.bitwise_or(arr_a, arr_b)

26. Statistical Operations:

numpy.percentile()

Computes the q-th percentile of the data.

percentile_50 = np.percentile(arr_a, 50)

numpy.var()

Computes the variance of the data.

variance = np.var(arr_a)

numpy.corrcoef()

Computes the Pearson correlation coefficient.

correlation_matrix = np.corrcoef(mat_a)

27. Handling NaN Values:

numpy.isnan()

Detects NaN values in an array.

nan_values = np.isnan(arr_a)

numpy.nan_to_num()

Replaces NaN values with zero and infinity with large finite numbers.

cleaned_arr = np.nan_to_num(arr_a)

28. Custom Mathematical Functions:

NumPy allows you to apply custom functions to each element of an array using numpy.vectorize().

def custom_function(x):
return x ** 2 + 2 * x + 1
custom_func_arr = np.vectorize(custom_function)(arr_a)

29. Memory Mapping:

NumPy supports memory-mapped arrays, which enable accessing large arrays stored on disk as if they were in memory.

mmapped_arr = np.memmap('large_data.dat', dtype='float64', mode='w+', shape=(1000, 1000))

30. Polynomial Operations:

NumPy provides functions for polynomial operations.

numpy.polyval()

Evaluates a polynomial at specific values.

coefficients = [1, -2, 1]
result = np.polyval(coefficients, 2)

numpy.polyfit()

Fits a polynomial of a specified degree to the data.

fit_coefficients = np.polyfit(arr_a, arr_b, 2)

31. Quantile Calculation:

numpy.quantile()

Computes the q-th quantile of the data.

quantile_25 = np.quantile(arr_a, 0.25)

In conclusion, NumPy is a fundamental library in Python that revolutionizes numerical computing and scientific data analysis. Its primary strength lies in the efficient handling of large, multi-dimensional arrays and matrices, enabling users to perform complex mathematical and statistical operations with ease. NumPy’s extensive set of functions covers a broad range of functionalities, from basic array manipulations and mathematical operations to advanced linear algebra, Fourier transforms, and statistical analyses. The array-oriented computing paradigm, coupled with its ability to seamlessly integrate with other scientific libraries, makes NumPy an essential tool for researchers, data scientists, and engineers. The library’s performance optimizations, including memory-efficient storage and vectorized operations, contribute to faster execution of computations. Overall, NumPy significantly enhances the speed, readability, and flexibility of numerical tasks in Python, playing a pivotal role in the success of scientific computing and data analysis workflows.

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

FARSHAD K
FARSHAD K

Written by FARSHAD K

Learning data science and machine learning with a strong curiosity in AI technologies and a drive to stay ahead in innovation.

No responses yet

Write a response