Skip to content

Slicing

Why Slicing?

Slicing is a powerful feature in NumPy that allows you to access a subset of elements from an array.

A real-world example:

Suppose we have a dataset of sales data for a company, where each row represents a month and each column represents a product. We can use slicing to access specific subsets of sales data.

import numpy as np

# Create a NumPy array with sales data
sales_data = np.array([
    [100, 200, 300],  # January
    [120, 250, 320],  # February
    [150, 300, 350],  # March
    [180, 350, 380],  # April
    [200, 400, 420],  # May
    [220, 450, 450]   # June
])

print("Sales Data: \n", sales_data)

# Access a subset of elements: Sales data for January to March
jan_to_mar_sales = sales_data[0:3, :]
print("Sales data for January to March: \n", jan_to_mar_sales)

# Access a subset of elements: Sales data for April to June
apr_to_jun_sales = sales_data[3:6, :]
print("Sales data for April to June: \n", apr_to_jun_sales)

# Access a subset of elements: Sales data for Product 1 and Product 2
product1_2_sales = sales_data[:, 0:2]
print("Sales data for Product 1 and Product 2: \n", product1_2_sales)

# Access a subset of elements: Sales data for Product 3
product3_sales = sales_data[:, 2]
print("Sales data for Product 3: ", product3_sales)

# Access a subset of elements: Sales data for January and June
jan_jun_sales = sales_data[[0, 5], :]
print("Sales data for January and June: \n", jan_jun_sales)

In this example, we create a NumPy array sales_data with sales data, where each row represents a month and each column represents a product. We then use slicing to access specific subsets of sales data.

  • We access a subset of elements: Sales data for January to March using sales_data[0:3, :].
  • We access a subset of elements: Sales data for April to June using sales_data[3:6, :].
  • We access a subset of elements: Sales data for Product 1 and Product 2 using sales_data[:, 0:2].
  • We access a subset of elements: Sales data for Product 3 using sales_data[:, 2].
  • We access a subset of elements: Sales data for January and June using sales_data[[0, 5], :].

key concepts

Here are some key concepts to keep in mind when using slicing:

  • array[start:stop, start:stop]: This syntax is used to access a subset of elements from an array. The start index is inclusive, and the stop index is exclusive.
  • array[start:, start:]: This syntax is used to access all elements from the start index to the end of the array.
  • array[:stop, :stop]: This syntax is used to access all elements from the beginning of the array to the stop index.
  • array[[index1, index2, ...], :]: This syntax is used to access specific rows from an array. The index1, index2, etc. are the indices of the rows to access.
  • array[:, [index1, index2, ...]]: This syntax is used to access specific columns from an array. The index1, index2, etc