codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐍

Python Programming

51 / 68 topics
51NumPy Tutorial52Pandas Tutorial53SciPy Tutorial54Matplotlib & Seaborn Basics55Machine Learning Basics (Stats & Data Distribution)56Linear & Polynomial Regression57Classification & Clustering (Decision Trees, K-Means)58TensorFlow & PyTorch Basics
Tutorials/Python Programming/NumPy Tutorial
🐍Python Programming

NumPy Tutorial

Updated 2026-05-15
30 min read

NumPy Tutorial

NumPy is a fundamental package for scientific computing with Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays efficiently. In this tutorial, we'll explore the core concepts of NumPy arrays (ndarray), how to create them, indexing/slicing, reshaping, mathematical operations, broadcasting, and aggregation functions.

Introduction

NumPy is essential for data science and machine learning because it allows you to perform complex numerical computations with ease. It provides a powerful N-dimensional array object called ndarray, which is optimized for performance and can handle large datasets efficiently. In this tutorial, we'll dive into the basics of NumPy arrays and explore various operations that make them indispensable in data analysis and machine learning tasks.

Creating Arrays

10.1. Using numpy.zeros

The numpy.zeros function creates an array filled with zeros. This is useful when you need to initialize an array without any specific values.

create_zeros.py
1import numpy as np
2
3# Create a 2x3 array of zeros
4zeros_array = np.zeros((2, 3))
5print(zeros_array)
Output
[[0. 0. 0.]
[0. 0. 0.]]

10.2. Using numpy.ones

The numpy.ones function creates an array filled with ones. This can be useful for initializing arrays where you want all elements to start at a specific value.

create_ones.py
1import numpy as np
2
3# Create a 3x2 array of ones
4ones_array = np.ones((3, 2))
5print(ones_array)
Output
[[1. 1.]
[1. 1.]
[1. 1.]]

10.3. Using numpy.arange

The numpy.arange function generates an array of evenly spaced values within a specified range. It's similar to Python's built-in range function but returns a NumPy array.

create_arange.py
1import numpy as np
2
3# Create an array with values from 0 to 9
4arange_array = np.arange(10)
5print(arange_array)
Output
[0 1 2 3 4 5 6 7 8 9]

10.4. Using numpy.linspace

The numpy.linspace function generates an array of evenly spaced values over a specified interval. This is useful when you need a specific number of points between two endpoints.

create_linspace.py
1import numpy as np
2
3# Create an array with 5 values from 0 to 1
4linspace_array = np.linspace(0, 1, 5)
5print(linspace_array)
Output
[0.   0.25 0.5  0.75 1.  ]

Indexing and Slicing

NumPy arrays can be indexed and sliced similar to Python lists, but with additional capabilities for multi-dimensional data.

10.5. Basic Indexing

You can access individual elements of a NumPy array using their indices.

indexing.py
1import numpy as np
2
3# Create a 2x3 array
4array = np.array([[1, 2, 3], [4, 5, 6]])
5
6# Access the element at row 0, column 1
7element = array[0, 1]
8print(element)
Output
2

10.6. Slicing

You can slice NumPy arrays to extract subarrays.

slicing.py
1import numpy as np
2
3# Create a 2x3 array
4array = np.array([[1, 2, 3], [4, 5, 6]])
5
6# Slice the first row
7row_slice = array[0, :]
8print(row_slice)
9
10# Slice the second column
11col_slice = array[:, 1]
12print(col_slice)
Output
[1 2 3]
[2 5]

Reshaping Arrays

NumPy arrays can be reshaped to change their dimensions while preserving the data.

10.7. Using numpy.reshape

The numpy.reshape function allows you to reshape an array to a new shape.

reshape.py
1import numpy as np
2
3# Create a 1D array
4array = np.array([1, 2, 3, 4, 5, 6])
5
6# Reshape the array to 2x3
7reshaped_array = array.reshape((2, 3))
8print(reshaped_array)
Output
[[1 2 3]
[4 5 6]]

10.8. Using numpy.ravel

The numpy.ravel function flattens an array into a single dimension.

ravel.py
1import numpy as np
2
3# Create a 2x3 array
4array = np.array([[1, 2, 3], [4, 5, 6]])
5
6# Flatten the array
7flattened_array = array.ravel()
8print(flattened_array)
Output
[1 2 3 4 5 6]

Mathematical Operations

NumPy provides a wide range of mathematical functions that can be applied to arrays.

10.9. Element-wise Operations

You can perform element-wise operations on NumPy arrays using arithmetic operators.

elementwise_operations.py
1import numpy as np
2
3# Create two arrays
4array1 = np.array([1, 2, 3])
5array2 = np.array([4, 5, 6])
6
7# Element-wise addition
8addition = array1 + array2
9print("Addition:", addition)
10
11# Element-wise multiplication
12multiplication = array1 * array2
13print("Multiplication:", multiplication)
Output
Addition: [5 7 9]
Multiplication: [ 4 10 18]

10.10. Broadcasting

Broadcasting allows NumPy to work with arrays of different shapes during arithmetic operations.

broadcasting.py
1import numpy as np
2
3# Create an array
4array = np.array([1, 2, 3])
5
6# Add a scalar to each element
7result = array + 5
8print(result)
Output
[6 7 8]

Aggregation Functions

NumPy provides several aggregation functions that can be used to perform operations on entire arrays.

10.11. Summation

The numpy.sum function calculates the sum of array elements.

sum.py
1import numpy as np
2
3# Create an array
4array = np.array([1, 2, 3, 4, 5])
5
6# Calculate the sum
7total_sum = np.sum(array)
8print(total_sum)
Output
15

10.12. Mean

The numpy.mean function calculates the mean of array elements.

mean.py
1import numpy as np
2
3# Create an array
4array = np.array([1, 2, 3, 4, 5])
5
6# Calculate the mean
7average = np.mean(array)
8print(average)
Output
3.0

Practical Example

Let's create a practical example that demonstrates how to use NumPy for data manipulation and analysis.

10.13. Data Analysis with NumPy

Suppose we have sales data for different products over several months, and we want to analyze this data using NumPy.

data_analysis.py
1import numpy as np
2
3# Sales data (rows: products, columns: months)
4sales_data = np.array([
5 [100, 200, 300],
6 [150, 250, 350],
7 [200, 300, 400]
8])
9
10# Calculate total sales for each product
11total_sales_per_product = np.sum(sales_data, axis=1)
12print("Total Sales per Product:", total_sales_per_product)
13
14# Calculate average sales across all products
15average_sales = np.mean(sales_data)
16print("Average Sales:", average_sales)
Output
Total Sales per Product: [600 750 900]
Average Sales: 250.0

Summary

ConceptDescription
ndarrayA multi-dimensional array object optimized for numerical computations.
Creating ArraysFunctions like numpy.zeros, numpy.ones, numpy.arange, and numpy.linspace.
Indexing/SlicingAccessing and extracting subarrays using indices and slices.
ReshapingChanging the shape of an array while preserving its data.
Mathematical OperationsElement-wise operations and broadcasting for efficient computations.
Aggregation FunctionsSummation, mean, and other functions to perform operations on entire arrays.

What's Next?

In the next tutorial, we'll explore Pandas, a powerful library for data manipulation and analysis. Pandas builds on NumPy and provides more advanced data structures like DataFrames, which are perfect for handling tabular data. This will be an excellent transition from numerical computations to data analysis tasks. Stay tuned!


PreviousPython MongoDB (Insert, Find, Update, Delete)Next Pandas Tutorial

Recommended Gear

Python MongoDB (Insert, Find, Update, Delete)Pandas Tutorial