Lesson 66 of 70 – Python NumPy
94%

Python NumPy

NumPy stands for Numerical Python. It is a popular Python library used for numerical computing, arrays, mathematical operations and scientific data processing.

Note: NumPy provides the ndarray data structure and many efficient functions for working with numerical data.
What is NumPy?

NumPy is an open-source Python library designed for efficient numerical computations.

It is widely used in data science, machine learning, scientific computing, engineering and data analysis.

  • Multidimensional arrays
  • Mathematical operations
  • Statistical calculations
  • Linear algebra
  • Random number generation
  • Array manipulation
Installing NumPy

NumPy can be installed using pip.

pip install numpy

You can also use:

python -m pip install numpy
Importing NumPy

NumPy is commonly imported using the alias np.

import numpy as np

The alias makes NumPy functions shorter and easier to write.

Creating a NumPy Array

The np.array() function creates a NumPy array.

import numpy as np

numbers = np.array([10, 20, 30, 40])

print(numbers)
Output:
[10 20 30 40]
Python List vs NumPy Array

Python lists and NumPy arrays can both store collections of values, but NumPy arrays are designed for efficient numerical operations and multidimensional data.

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

print(numbers * 2)
Output:
[2 4 6 8]

NumPy performs the operation element by element.

Array Dimensions

NumPy arrays can have different numbers of dimensions.

0-D Array:

a = np.array(10)

1-D Array:

a = np.array([10, 20, 30])

2-D Array:

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

3-D Array:

a = np.array([
    [
        [1, 2],
        [3, 4]
    ]
])
Checking Dimensions with ndim

The ndim attribute returns the number of dimensions of an array.

import numpy as np

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

print(a.ndim)
Output:
2
Array Shape

The shape attribute returns the size of the array along each dimension.

import numpy as np

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

print(a.shape)
Output:
(2, 3)

This means the array contains 2 rows and 3 columns.

Array Size

The size attribute returns the total number of elements.

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

print(a.size)
Output:
6
Array Data Type

The dtype attribute tells you the data type of the array elements.

a = np.array([10, 20, 30])

print(a.dtype)

The exact displayed dtype depends on the values and NumPy/platform details.

Creating Arrays with arange()

The np.arange() function creates evenly spaced values within a specified range.

import numpy as np

numbers = np.arange(1, 6)

print(numbers)
Output:
[1 2 3 4 5]

The stop value is not included.

Creating Arrays with zeros()

The np.zeros() function creates an array filled with zeros.

import numpy as np

numbers = np.zeros(5)

print(numbers)
Output:
[0. 0. 0. 0. 0.]
Creating Arrays with ones()

The np.ones() function creates an array filled with ones.

numbers = np.ones(5)

print(numbers)
Output:
[1. 1. 1. 1. 1.]
Creating an Empty Array

The np.empty() function creates an array without explicitly initializing its elements to a particular value. The initial values are not guaranteed to be zero.

numbers = np.empty(5)

print(numbers)
Important: The values returned by empty() should not be treated as meaningful initial data. Assign values before using them.
linspace()

The np.linspace() function creates a specified number of evenly spaced values over an interval.

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

print(numbers)
Output:
[ 0.   2.5  5.   7.5 10. ]
Indexing NumPy Arrays

NumPy arrays use zero-based indexing.

numbers = np.array([10, 20, 30, 40])

print(numbers[0])
print(numbers[2])
Output:
10
30
Negative Indexing

Negative indexes access elements from the end of the array.

numbers = np.array([10, 20, 30, 40])

print(numbers[-1])
print(numbers[-2])
Output:
40
30
Slicing Arrays

Array slicing is used to select a range of elements.

numbers = np.array([10, 20, 30, 40, 50])

print(numbers[1:4])
Output:
[20 30 40]
2-D Array Indexing

For a 2-D array, indexes can be used for both row and column.

numbers = np.array([
    [10, 20, 30],
    [40, 50, 60]
])

print(numbers[0, 1])
print(numbers[1, 2])
Output:
20
60
Array Arithmetic

NumPy allows arithmetic operations to be performed element by element.

a = np.array([10, 20, 30])

print(a + 5)
print(a * 2)
print(a - 3)
Example Output:
[15 25 35]
[20 40 60]
[ 7 17 27]
Operations Between Arrays
a = np.array([10, 20, 30])

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

print(a + b)
print(a * b)
Output:
[11 22 33]
[10 40 90]
NumPy Mathematical Functions

NumPy provides many mathematical functions.

numbers = np.array([1, 4, 9, 16])

print(np.sqrt(numbers))
Output:
[1. 2. 3. 4.]

Other useful functions include np.sin(), np.cos(), np.exp() and np.log().

Sum, Minimum and Maximum
numbers = np.array([10, 20, 30, 40])

print(np.sum(numbers))
print(np.min(numbers))
print(np.max(numbers))
Output:
100
10
40
Mean and Standard Deviation
numbers = np.array([10, 20, 30, 40])

print(np.mean(numbers))
print(np.std(numbers))

The mean() function calculates the arithmetic average and std() calculates the standard deviation.

Reshaping an Array

The reshape() method changes the shape of an array without changing its data.

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

matrix = numbers.reshape(2, 3)

print(matrix)
Output:
[[1 2 3]
 [4 5 6]]
Flattening an Array

The flatten() method returns a flattened copy of an array.

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

numbers = matrix.flatten()

print(numbers)
Output:
[1 2 3 4]
Concatenating Arrays

The np.concatenate() function joins arrays along an existing axis.

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

b = np.array([4, 5, 6])

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

print(result)
Output:
[1 2 3 4 5 6]
Stacking Arrays

NumPy provides functions such as vstack() and hstack() for combining arrays along different dimensions.

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

b = np.array([4, 5, 6])

print(np.vstack((a, b)))
Output:
[[1 2 3]
 [4 5 6]]
Sorting Arrays

The np.sort() function returns a sorted copy of an array.

numbers = np.array([40, 10, 30, 20])

result = np.sort(numbers)

print(result)
Output:
[10 20 30 40]
Filtering Arrays

Boolean conditions can be used to filter NumPy arrays.

numbers = np.array([10, 20, 30, 40, 50])

result = numbers[numbers > 25]

print(result)
Output:
[30 40 50]
Random Numbers

NumPy provides a random number module for generating random values.

import numpy as np

numbers = np.random.randint(
    1,
    10,
    size=5
)

print(numbers)

The values will vary each time the program runs.

Random Floating-Point Numbers
numbers = np.random.rand(5)

print(numbers)

This generates five random floating-point values in the interval from 0 up to but not including 1.

Linear Algebra

NumPy also provides functions for linear algebra operations.

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

print(np.linalg.det(a))

The numpy.linalg module provides functions for matrix and linear algebra calculations.

NumPy and Data Science

NumPy is an important foundation for the Python data science ecosystem. Many libraries use NumPy arrays or concepts built around numerical arrays.

  • Pandas
  • Matplotlib
  • Scikit-learn
  • Scientific computing tools
  • Machine learning libraries
Common NumPy Mistakes
  • Forgetting to install NumPy.
  • Forgetting to import NumPy.
  • Confusing array shape with array size.
  • Using incompatible shapes in array operations.
  • Accessing an index outside the array range.
  • Assuming np.empty() initializes an array with zeros.
  • Forgetting that many NumPy operations return a new array rather than modifying the original.
Complete NumPy Example
import numpy as np

numbers = np.array([
    10, 20, 30, 40, 50
])

print("Array:", numbers)

print("Sum:", np.sum(numbers))

print("Average:", np.mean(numbers))

print("Maximum:", np.max(numbers))

print("Minimum:", np.min(numbers))

print("Greater than 25:",
      numbers[numbers > 25])
Example Output:
Array: [10 20 30 40 50]
Sum: 150
Average: 30.0
Maximum: 50
Minimum: 10
Greater than 25: [30 40 50]
Key Points
  • NumPy stands for Numerical Python.
  • NumPy is widely used for numerical and scientific computing.
  • NumPy is commonly imported as np.
  • np.array() creates NumPy arrays.
  • ndim returns the number of dimensions.
  • shape returns the dimensions of an array.
  • size returns the total number of elements.
  • dtype shows the element data type.
  • arange() creates evenly spaced values using a step.
  • linspace() creates a specified number of evenly spaced values.
  • zeros() creates arrays filled with zeros.
  • ones() creates arrays filled with ones.
  • NumPy supports multidimensional arrays.
  • Arrays support efficient element-wise numerical operations.
  • NumPy provides mathematical and statistical functions.
  • reshape() changes the shape of an array.
  • Boolean indexing can be used to filter arrays.
  • NumPy provides random-number and linear-algebra functionality.
  • NumPy is an important library for Python data science.

🧠 Quick Quiz

Question: Which function is commonly used to create a NumPy array?