Posts

Showing posts with the label Slicing

Basic Array Operations: Slicing, Indexing, and Reshaping NumPy Arrays

  Basic Array Operations: Slicing, Indexing, and Reshaping NumPy Arrays Welcome back, data wranglers! In our previous discussions, we've explored what NumPy arrays are and the immense power of vectorization for performing lightning-fast operations on entire datasets. But what if you don't want to operate on the entire array? What if you need to access specific elements, extract subsets, or change the layout of your data? This is where indexing, slicing, and reshaping come into play. These fundamental operations allow you to precisely manipulate your NumPy arrays, making them incredibly versatile for data cleaning, analysis, and preparation for machine learning models. 1. Indexing: Accessing Individual Elements Just like Python lists, NumPy arrays use zero-based indexing to access individual elements. 1.1. One-Dimensional (1D) Arrays: Accessing elements in a 1D array is straightforward: Python import numpy as np arr = np.array([ 10 , 20 , 30 , 40 , 50 ]) print( f"Firs...