NumPy Array Operations: Slicing, Indexing, and Reshaping


Essential NumPy Array Operations

NumPy arrays are the backbone of scientific computing in Python. These operations are fundamental:

1. Element-wise Operations

These apply functions or operations to each element of an array individually, or between corresponding elements of two arrays. They are much faster than Python loops.

  • Scalar Operations:

    Python
    import numpy as np
    
    arr = np.array([1, 2, 3])
    print("Original:", arr)
    print("Add 5:", arr + 5)     # Output: [6 7 8]
    print("Multiply by 2:", arr * 2) # Output: [2 4 6]
    print("Square:", arr ** 2)   # Output: [1 4 9]
    
  • Array-Array Operations:

    Python
    arr1 = np.array([1, 2, 3])
    arr2 = np.array([4, 5, 6])
    print("Arr1 + Arr2:", arr1 + arr2) # Output: [5 7 9]
    print("Arr1 * Arr2:", arr1 * arr2) # Output: [ 4 10 18]
    

2. Aggregation Functions

Aggregations perform a calculation on an array (or a part of it) to return a single value.

FunctionDescription
sum()Sum of elements
mean()Average value
max()Maximum value
min()Minimum value
std()Standard deviation
  • Examples:

    Python
    data = np.array([[1, 2, 3],
                     [4, 5, 6]])
    print("\nData:\n", data)
    print("Sum of all elements:", data.sum())        # Output: 21
    print("Mean of all elements:", data.mean())       # Output: 3.5
    print("Max along rows (axis=1):", data.max(axis=1)) # Output: [3 6]
    print("Min along columns (axis=0):", data.min(axis=0)) # Output: [1 2 3]
    
    • axis=0: Operation across rows (columns are preserved).

    • axis=1: Operation across columns (rows are preserved).

3. Broadcasting

Broadcasting describes how NumPy handles arrays of different shapes during arithmetic operations. It allows operations between arrays that would normally have incompatible shapes.

  • Rule: When operating on two arrays, NumPy compares their shapes element-wise, starting from the trailing dimension. Dimensions are compatible if:

    1. They are equal.

    2. One of them is 1.

Array 1 ShapeArray 2 ShapeResult ShapeBroadcastable?
(3, 4)(1, 4)(3, 4)Yes
(3, 4)(3, 1)(3, 4)Yes
(3, 4)(4,)(3, 4)Yes
(3, 4)(3,)ErrorNo
  • Examples:

    Python
    matrix = np.array([[10, 20, 30],
                       [40, 50, 60]]) # Shape (2, 3)
    vector = np.array([1, 2, 3])     # Shape (3,)
    
    # Vector is broadcast across rows of the matrix
    result = matrix + vector
    print("\nMatrix + Vector (Broadcast):\n", result)
    # Output:
    # [[11 22 33]
    #  [41 52 63]]
    
    # Adding a column vector
    col_vector = np.array([[100], [200]]) # Shape (2, 1)
    result_col = matrix + col_vector
    print("Matrix + Column Vector (Broadcast):\n", result_col)
    # Output:
    # [[110 120 130]
    #  [240 250 260]]
    

Understanding these operations is crucial for efficient data processing and numerical computations in Python using NumPy.


Useful Video Links

  • NumPy Tutorial - FULL COURSE: Covers all basics, including element-wise operations, aggregation, and broadcasting.

    • [suspicious link removed] (Please search YouTube for the exact video if the direct link is not available)

  • NumPy Broadcasting Explained: A focused video on this powerful concept.

    • [suspicious link removed] (Please search YouTube for the exact video if the direct link is not available)

  • NumPy Array Aggregation Functions: Deep dive into sum(), mean(), max(), min(), etc., with axis explanations.

    • [suspicious link removed] (Please search YouTube for the exact video if the direct link is not available)


Comments

Popular posts from this blog

Virtual Environments: Keeping Your Data Science Projects Clean and Sane

Python Decorators: Enhancing Your Data Functions with a Dash of Magic

Linear Algebra with NumPy: Dot Products & Matrix Multiplication