DEV Community

Lameck Odhiambo
Lameck Odhiambo

Posted on

Understanding NumPy

  • Numerical Python also known as Numpy is used for numerical computing in Data Science, Engineering, Artificial Intelligence and Machine Learning
  • Clean python lists cannot be compared to ndarrays of numpy which are faster.

Getting started with numpy

  • If you have Python and PIP already installed on a system, then installation of NumPy is very easy.

Install it using this command:

pip install numpy
Enter fullscreen mode Exit fullscreen mode
  • Once NumPy is installed, import it in your applications by adding the import keyword
import numpy as np
Enter fullscreen mode Exit fullscreen mode

Checking NumPy Version
The version string is stored under version attribute.

import numpy as np

print(np.__version__)
Enter fullscreen mode Exit fullscreen mode

Creating Arrays in Numpy

  • NumPy is used to work with arrays. The array object in NumPy is called ndarray.
  • We can create a NumPy ndarray object by using the array() function. import numpy as np

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

print(arr)

print(type(arr))
Enter fullscreen mode Exit fullscreen mode

Output:

[1 2 3 4 5]
<class 'numpy.ndarray'>
Enter fullscreen mode Exit fullscreen mode

Dimensions in Arrays

1-D Arrays

  • An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
import numpy as np

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

print(arr)
Enter fullscreen mode Exit fullscreen mode

Output:

[1 2 3 4 5]
Enter fullscreen mode Exit fullscreen mode

2-D Arrays

  • An array that has 1-D arrays as its elements is called a 2-D array.
import numpy as np

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

print(arr)
Enter fullscreen mode Exit fullscreen mode

Output:

[[1 2 3]
 [4 5 6]]
Enter fullscreen mode Exit fullscreen mode

3-D arrays

  • An array that has 2-D arrays (matrices) as its elements is called 3-D array.
import numpy as np

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

print(arr)
Enter fullscreen mode Exit fullscreen mode

Check Number of Dimensions

  • NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have.
import numpy as np

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

print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
Enter fullscreen mode Exit fullscreen mode

Output:

0
1
2
3
Enter fullscreen mode Exit fullscreen mode

Indexing and Slicing

  • The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
  • Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end]. We can also define the step, like this: [start:end:step].
import numpy as np

arr = np.array([
    [10, 11, 12, 13],
    [20, 21, 22, 23],
    [30, 31, 32, 33]
])
Enter fullscreen mode Exit fullscreen mode
  1. Accessing Rows
  • Single Row: Pass the zero-based index of the row
arr[0]      # Returns the 1st row: [10, 11, 12, 13]
arr[-1]     # Returns the last row:  [30, 31, 32, 33]
Enter fullscreen mode Exit fullscreen mode
  • Range of Rows: Use a slice for the row position. The end index is exclusive
arr[0:2]    # Returns rows 0 and 1 (first two rows)
Enter fullscreen mode Exit fullscreen mode
  1. Accessing Columns

To extract columns, you must tell NumPy to look at all rows by using a standalone colon (:) in the row slot, followed by your column index.

Single Column

arr[:, 1]   # Returns the 2nd column: [11, 21, 31]
Enter fullscreen mode Exit fullscreen mode

Range of Columns

arr[:, 1:3] # Returns columns 1 and 2 across all rows
Enter fullscreen mode Exit fullscreen mode

Arithmetic

Scalar arithmetic

  • Scalar arithmetic in NumPy refers to performing standard mathematical operations between a single numerical value (a scalar) and a NumPy array.
import numpy as np

# Create a simple 1D array
arr = np.array([10, 20, 30, 40])
scalar = 5

# 1. Addition
print("Addition (+):", arr + scalar)
# Output: [15 25 35 45]

# 2. Subtraction
print("Subtraction (-):", arr - scalar)
# Output: [ 5 15 25 35]

# 3. Multiplication
print("Multiplication (*):", arr * scalar)
# Output: [ 50 100 150 200]

# 4. Division (returns floats)
print("Division (/):", arr / scalar)
# Output: [2.  4.  6.  8.]

# 5. Exponentiation (Power)
print("Power (**):", arr ** 2)
# Output: [ 100  400  900 1600]
Enter fullscreen mode Exit fullscreen mode

Element-Wise Arithmetic (Same Shape)

When you use standard mathematical operators (+, -, , /, *) on two arrays of the same shape, NumPy automatically applies the operation to corresponding elements

import numpy as np

a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])

# Element-wise addition
print(a + b)  # Output: [11 22 33 44]

# Element-wise multiplication
print(a * b)  # Output: [10 40 90 160]
Enter fullscreen mode Exit fullscreen mode

Universal Functions (uFuncs)

NumPy provides built-in functions (called ufuncs) designed to execute vectorized operations across entire arrays for more complex math

angles = np.array([0, np.pi/2, np.pi])

# Vectorized sine calculation
print(np.sin(angles))  # Output: [0.0000000e+00 1.0000000e+00 1.2246468e-16]

# Vectorized square root
values = np.array([4, 9, 16])
print(np.sqrt(values))  # Output: [2. 3. 4.]
Enter fullscreen mode Exit fullscreen mode

Broadcasting (Different Shapes)

  • If you attempt arithmetic on two arrays with different shapes, NumPy uses its Broadcasting Rules to implicitly "stretch" the smaller array across the larger one so their dimensions match
matrix = np.array([[1, 2, 3], 
                   [4, 5, 6]])
row_vector = np.array([10, 20, 30])

# The row vector is automatically broadcasted down both rows of the matrix
print(matrix + row_vector)
# Output:
# [[11 22 33]
#  [14 25 36]]
Enter fullscreen mode Exit fullscreen mode

Comparison Operators

  • In NumPy, comparison operators perform element-wise evaluations on arrays, returning a Boolean array (True or False) of the same shape.
  1. Comparing an Array with a Scalar
  2. NumPy automatically broadcasts the scalar value across every element in the array
import numpy as np

arr = np.array([10, 20, 30, 40])
print(arr > 25) 
# Output: [False False  True  True]
Enter fullscreen mode Exit fullscreen mode
  1. Comparing Two Arrays
  2. Arrays must have matching or compatible shapes. The comparison happens between corresponding element pairs
a = np.array([1, 5, 3])
b = np.array([2, 4, 3])

print(a == b) 
# Output: [False False  True]
Enter fullscreen mode Exit fullscreen mode
  1. Filtering Data (Boolean Masking)
  2. You can use the resulting Boolean array to index or filter the original array
arr = np.array([5, 12, 8, 21])
filtered_arr = arr[arr > 10]

print(filtered_arr) 
# Output: [12 21]
Enter fullscreen mode Exit fullscreen mode
  1. Combining Conditions

Standard Python logical operators (and, or) do not work on entire NumPy arrays. Instead, use bitwise operators (&, |, ~) or NumPy functions like np.logical_and(). Always wrap individual comparisons in parentheses

arr = np.array([5, 12, 18, 25])
# Find elements greater than 10 AND less than 20
mask = (arr > 10) & (arr < 20)

print(arr[mask]) 
# Output: [12 18]
Enter fullscreen mode Exit fullscreen mode

Aggregate Functions

  • Aggregate functions in NumPy (also known as reductions) take an array of values and summarize them into a single value or a reduced set of values
prices = np.array([10, 25, 40, 15, 60])

print("--- 1D Array Basics ---")
print("Total Sum :", np.sum(prices))   # Adds all elements: 10 + 25 + 40 + 15 + 60
print("Average   :", np.mean(prices))  # Finds the average: 150 / 5
print("Lowest    :", np.min(prices))   # Finds the smallest value
print("Highest   :", np.max(prices))   # Finds the largest value
Enter fullscreen mode Exit fullscreen mode

Filtering

  • np.where() and np.select() are conditional operations used to transform or filter data based on specific criteria. While np.where() evaluates a single condition to choose between two paths, np.select() evaluates an ordered list of multiple conditions to choose from multiple options.

  • The np.where(condition, x, y) function returns elements from x when the condition is True, and from y when it is False.

import numpy as np

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

# If an element is greater than 25, keep it; otherwise, replace it with 0
result = np.where(arr > 25, arr, 0)

print(result)
# Output: [ 0  0 30 40 50]
Enter fullscreen mode Exit fullscreen mode
  • The np.select(condlist, choicelist, default=0) function maps an ordered list of conditions to a corresponding list of outcomes. It evaluates them in order and stops at the first True condition it hits
import numpy as np

arr = np.array([5, 15, 25, 35, 45])

# Define a list of criteria
conditions = [
    arr < 10,                 # Condition 1
    (arr >= 10) & (arr < 30), # Condition 2
    arr >= 30                 # Condition 3
]

# Define what to assign for each true condition
choices = [
    'Low',
    'Medium',
    'High'
]

# Apply the mapping, using a default value for unmatched entries
result = np.select(conditions, choices, default='Unknown')

print(result)
# Output: ['Low' 'Medium' 'Medium' 'High' 'High']
Enter fullscreen mode Exit fullscreen mode

Conclusion

NumPy is the foundational library for scientific computing in Python, providing the essential structure for data science and machine learning. At its core is the ndarray, a multi-dimensional array object that enables lightning-fast mathematical computations by storing data in contiguous memory and using compiled C code. By supporting vectorized operations and broadcasting, it eliminates the need for slow, explicit Python loops, allowing developers to manipulate massive datasets efficiently. Because of this speed and versatility, NumPy serves as the critical backbone powering almost all major Python data libraries, including Pandas, SciPy, Scikit-learn, and TensorFlow.

Top comments (0)