close
close
numpy cheatsheet

numpy cheatsheet

5 min read 21-10-2024
numpy cheatsheet

NumPy Cheatsheet: Mastering the Power of Python Arrays

NumPy, the cornerstone of scientific computing in Python, provides powerful array manipulation capabilities that are essential for data scientists, machine learning engineers, and anyone working with numerical data. This cheatsheet serves as a concise guide to commonly used NumPy functions, empowering you to perform efficient operations on arrays.

Creating Arrays

How do I create a NumPy array?

import numpy as np

# From a list
array_from_list = np.array([1, 2, 3, 4])

# Using arange()
array_from_range = np.arange(10)  # Creates an array from 0 to 9

# Creating a multidimensional array
multi_array = np.array([[1, 2], [3, 4]]) 

# Creating an array of zeros
zeros_array = np.zeros((3, 3)) 

# Creating an array of ones
ones_array = np.ones((2, 2))

# Creating an array filled with a specific value
constant_array = np.full((2, 2), 5)

# Creating an array with random values
random_array = np.random.rand(3, 3)

Explanation:

  • np.array(): This is the most common way to create a NumPy array from a Python list or tuple.
  • np.arange(): Creates an array with evenly spaced values within a given range.
  • np.zeros() and np.ones(): Generate arrays filled with zeros and ones, respectively, with specified dimensions.
  • np.full(): Creates an array filled with a constant value.
  • np.random.rand(): Generates an array of random values within a given shape.

Array Manipulation

How can I access and modify elements in a NumPy array?

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

# Accessing elements by index
first_element = array[0]  # Output: 1
last_element = array[-1]  # Output: 4

# Slicing: Accessing a subset of elements
subset = array[1:3]  # Output: array([2, 3])

# Reshaping the array
reshape_array = array.reshape(2, 2)

# Transposing the array
transposed_array = array.transpose()

# Concatenating arrays
concatenated_array = np.concatenate((array, np.array([5, 6])))

Explanation:

  • Indexing: Use square brackets to access individual elements, starting from zero.
  • Slicing: Use a colon to select a range of elements.
  • Reshaping: Modify the dimensions of the array using reshape().
  • Transposing: Swap rows and columns using transpose().
  • Concatenation: Combine arrays along a specific axis using concatenate().

Mathematical Operations

How do I perform mathematical operations on NumPy arrays?

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

# Addition
sum_array = array1 + array2  # Output: array([5, 7, 9])

# Subtraction
diff_array = array1 - array2  # Output: array([-3, -3, -3])

# Multiplication
product_array = array1 * array2  # Output: array([4, 10, 18])

# Division
division_array = array1 / array2  # Output: array([0.25, 0.4, 0.5])

# Dot product
dot_product = np.dot(array1, array2)  # Output: 32

# Element-wise square root
sqrt_array = np.sqrt(array1)  # Output: array([1., 1.41421356, 1.73205081])

Explanation:

  • NumPy allows element-wise operations on arrays, performing the operation on each corresponding element.
  • np.dot() calculates the dot product of two arrays.
  • NumPy provides a wide range of mathematical functions like sqrt(), sin(), cos(), log(), etc., which can be applied to arrays for element-wise calculations.

Aggregations and Statistics

How can I calculate statistics on NumPy arrays?

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

# Sum
sum_value = np.sum(array)  # Output: 15

# Mean
mean_value = np.mean(array)  # Output: 3.0

# Standard Deviation
std_dev = np.std(array)  # Output: 1.58113883

# Minimum and Maximum
min_value = np.min(array)  # Output: 1
max_value = np.max(array)  # Output: 5

# Median
median_value = np.median(array)  # Output: 3

# Variance
variance = np.var(array)  # Output: 2.5

Explanation:

  • NumPy provides functions for common statistical calculations, including:
    • np.sum(): Calculates the sum of all elements.
    • np.mean(): Finds the average of all elements.
    • np.std(): Determines the standard deviation.
    • np.min() and np.max(): Returns the minimum and maximum values.
    • np.median(): Calculates the median value.
    • np.var(): Returns the variance of the elements.

Advanced Operations

How can I utilize more advanced NumPy operations?

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

# Sorting
sorted_array = np.sort(array) # Output: array([1, 2, 3, 4, 5])

# Finding unique elements
unique_elements = np.unique(array) # Output: array([1, 2, 3, 4, 5])

# Searching for elements
index = np.where(array == 3) # Output: (array([2]),)

# Broadcasting: Performing operations on arrays with different shapes
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([5, 6])
broadcasted_result = array1 + array2 # Output: array([[ 6,  8], [ 8, 10]])

# Linear Algebra: Solving systems of equations
A = np.array([[1, 2], [3, 4]])
b = np.array([5, 6])
solution = np.linalg.solve(A, b) # Output: array([-1.,  3.])

Explanation:

  • np.sort(): Sorts the elements of the array in ascending order.
  • np.unique(): Returns an array containing only the unique elements.
  • np.where(): Finds the indices of elements that satisfy a given condition.
  • Broadcasting: NumPy can automatically expand the dimensions of smaller arrays to match the larger array during arithmetic operations.
  • Linear Algebra: NumPy provides functions for linear algebra operations like solving systems of equations using np.linalg.solve().

Example: Image Processing with NumPy

Imagine you are working with an image represented as a NumPy array. You can use NumPy to manipulate the image data and perform various operations:

  1. Grayscale Conversion:
import numpy as np
import matplotlib.pyplot as plt

image = plt.imread("image.jpg")
gray_image = np.dot(image[...,:3], [0.299, 0.587, 0.114]) # Convert to grayscale
plt.imshow(gray_image, cmap="gray")
plt.show()
  1. Brightness Adjustment:
# Increase the brightness by 50%
adjusted_image = image * 1.5
plt.imshow(adjusted_image)
plt.show()
  1. Noise Reduction:
# Apply a Gaussian filter to reduce noise
from scipy.ndimage import gaussian_filter
smoothed_image = gaussian_filter(image, sigma=2) # Adjust sigma for desired smoothing
plt.imshow(smoothed_image)
plt.show()

These are just a few examples of how NumPy can be used for image processing. Its array capabilities make it a versatile tool for manipulating and analyzing image data.

Conclusion

This cheatsheet provides a foundation for understanding and utilizing NumPy's powerful array manipulation capabilities. By mastering these techniques, you can efficiently process numerical data, perform complex mathematical operations, and achieve your scientific computing goals. Remember, practice is key! Explore NumPy's documentation and experiment with these examples to gain a deeper understanding of this essential Python library.

Note: This article was created using content from Github repositories. Please refer to the original sources for more detailed explanations and examples:

Related Posts


Latest Posts