Shape Manipulation and Sorting

NumPy provides powerful tools for reshaping, transposing, and sorting arrays, allowing you to manipulate data structures to fit your specific needs.

Reshaping Arrays

Reshaping: Changing the shape of an array while preserving its elements.

Python

import numpy as np

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

# Reshape into a 2x3 matrix
reshaped = arr.reshape(2, 3)

Flattening: Converting a multidimensional array into a 1D array.

Python

flattened = arr.flatten()

Resizing: Changing the size of an array, potentially adding or removing elements.

Python

resized = np.resize(arr, (4, 2))

Transposing Arrays

Transposing: Swapping the dimensions of an array.

Python

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

transposed = arr2d.T

Sorting Arrays

Sorting along an Axis: Sorting the elements of an array along a specified axis.

Python

sorted_arr = np.sort(arr)  # Sort along the default axis (0)

# Sort along the first axis (rows)
sorted_arr = np.sort(arr2d, axis=0)

Sorting in Place: Modifying the original array in-place.

Python

arr.sort()

Custom Sorting: Sorting using a custom comparison function.

Python

def my_compare(x, y):
    return x - y

sorted_arr = np.sort(arr, kind='mergesort', order=my_compare)

Advanced Shape Manipulation

Stacking: Combining multiple arrays along a new axis.

Python

stacked = np.vstack((arr1, arr2))  # Vertical stacking
stacked = np.hstack((arr1, arr2))  # Horizontal stacking

Concatenation: Joining arrays along an existing axis.

Python

concatenated = np.concatenate((arr1, arr2), axis=0)

Splitting: Dividing an array into multiple subarrays along an axis.

Python

split = np.split(arr, 2)

By mastering shape manipulation and sorting techniques, you can effectively reshape, transpose, and sort NumPy arrays to suit your data analysis needs.

Understand Reduction Functions
Data Types: Size, Casting, and Structure

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?