Slicing in NumPy allows you to extract a subset of elements from an array by specifying a range of indices. 

It is similar to slicing in Python lists but more powerful when dealing with multidimensional arrays.

For example, think of an orange. A single orange has multiple slices. Here, the complete orange is like a Numpy array, and its slices are the pieces of data. Similarly, in a Numpy array, slicing lets us take out parts of the array, just like taking a slice from an orange.

Syntax for Numpy slicing:

array[start:stop:increment]

In the slicing, there are some default values for its three parameters. These values are used when we do not pass specific values to the function:

  • start: 0 (the sequence starts from 0)
  • end: n−1 (the sequence ends at n−1)
  • step: 1 (the sequence increases by 1 each time)

 

Slicing a 1D Array:

Example:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])

# Extract elements from index 1 to 3
sliced_array = arr[1:4]
print(sliced_array)

Output:

[20 30 40]

 

Note: always remember when we leave slicing blank i.e. (:) it means all.

For Example: 

In this example, I am not passing the start value; I leave that blank, which means the start starts from zero because its default value is 0.

import numpy as np

my_arr = np.array([12, 34, 45, 56, 67, 78])
print("Orignal Array : ", my_arr)

new_arr = my_arr[ : 4]

print("sliced_array : ", new_arr)

Output:

Orignal Array :  [12 34 45 56 67 78]

sliced_array :  [12 34 45 56]

 

Slicing with a Steps in Numpy array:

In this example, we keep the start and end elements as blank by ( : ), and set the increment value to 2. This means it starts from index 0 and continues to the last element index, but the increment of the indexes is now 2.

import numpy as np

my_arr = np.array([12, 34, 45, 56, 67, 78, 3, 4, 9])
print("Orignal Array : ", my_arr)

new_arr = my_arr[ : : 2]

print("sliced_array : ", new_arr)

Output:

Orignal Array :  [12 34 45 56 67 78  3  4  9]
sliced_array :  [12 45 67  3  9]

 

Let's move on to the higher dimensions:
Slicing with 2D array:

Syntax: We have 2 syntaxes for 2-D array slicing:

array_name[array_index, elements_slicing]
                OR
array_name[array_index][elements_slicing]

Example, we have an array:

import numpy as np

zx = np.array([[12, 34, 4, 5], [5, 3, 2, 5], [34, 6, 1, 34]])

print(zx)

And we want to get this piece of d data.

[[12 34  4  5]
 [ 5  3  2  5]
 [34  6  1 34]]

Solution:

import numpy as np
zx = np.array([[12, 34, 4, 5], [5, 3, 2, 5], [34, 6, 1, 34]])

print(zx[1][1:4])

Output:

[3 2 5]


 

15+ interview questions about NumPy slicing

Question 1: Explain slicing in NumPy.

Answer: Slicing in NumPy allows accessing parts of an array by specifying a range of indices. The syntax is array[start:stop:step].

Example:

import numpy as np
arr = np.array([0, 1, 2, 3, 4, 5])

print(arr[1:4])  # Slicing from index 1 to 3

Output: 

[1 2 3]

 

Question 2: How do you slice a 2D array?

Given the array:

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

Slice the first two rows and the first two columns.

Solution:

print(arr[:2, :2])  # Slice first 2 rows and columns

Output: 

[[1 2]
 [4 5]]

 

Question 3: Extract every other element from a 1D array. 

Slice the array [10, 20, 30, 40, 50, 60] to extract every other element.

Solution:

import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60])

print(arr[::2])  # Extract every second element

Output: 

[10 30 50]

 

Question 4: Reverse a 1D array using slicing.

Example: Reverse the array [1, 2, 3, 4, 5] using slicing.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr[::-1])  # Reverse the array

Output: 

[5 4 3 2 1]

 

Question 5: Slice a specific row from a 2D array.

Given the array:

import numpy as np

arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])

Problem: Extract the second row.

Solution:

print(arr[1, :])  # Extract the second row

Output: 

[40 50 60]

 

Question 6: Extract a specific column from a 2D array.

Given the array:

import numpy as np

arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])

Problem: Extract the third column.

Solution:

import numpy as np

arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])

print(arr[:, 2])  # Extract the third column

Output: 

[30 60 90]

 

Question 7: Slice the last two elements from each row in a 2D array.

Given the array:

import numpy as np

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

Problem: Extract the last two elements from each row.

Solution:

print(arr[:, -2:])  # Last two elements of each row

Output: 

[[2 3]
 [5 6]
 [8 9]]

 

Question 8: Localized: Extract diagonal elements using slicing.

We have a 3x3 array:

import numpy as np

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

Problem: Extract the diagonal elements [1, 5, 9] using slicing.

Example:

print(arr[range(3), range(3)])  # Diagonal elements

Output: 

[1 5 9]

 

Question 9: Extract subarray from the middle of a 2D array.

From the array:

import numpy as np

arr = np.array([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]])

Problem: Extract the 2x2 subarray [[60, 70], [100, 110]].

Solution:

print(arr[1:3, 1:3])  # Middle subarray

 

Output: 

[[ 60  70]
 [100 110]]

 

Question 10: Skip rows while slicing.

Given the array:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])

Problem: Extract every other row.

Example:

print(arr[::2, :])  # Skip rows

Output: 

[[1 2 3]
 [7 8 9]]

 

Question 11: Extract elements divisible by 3.

Problem: We have the array [1, 2, 3, 4, 5, 6, 7, 8, 9]. Find elements divisible by 3.

Solution:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print(arr[arr % 3 == 0])  # Divisible by 3

Output: 

[3 6 9]

 

Question 12: Extract alternate columns from a 2D array.

From the array:

import numpy as np

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

Problem: Extract alternate columns.

Solution:

print(arr[:, ::2])  # Alternate columns

Output: 

[[1 3]
 [4 6]
 [7 9]]

 

Question 13: Localized: Extract upper triangle elements.

From the array:

import numpy as np

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

Problem: Extract upper triangle elements [1, 2, 3, 5, 6, 9].

Example:

print(arr[np.triu_indices_from(arr)])  # Upper triangle

Output: 

[1 2 3 5 6 9]

 

Question 14: Slice using negative indices.

From the array [10, 20, 30, 40, 50, 60], slice the last three elements.

Example:

import numpy as np

arr = np.array([10, 20, 30, 40, 50, 60])
print(arr[-3:])  # Last three elements

Output: 

[40 50 60]

 

Question 15: Find sum of a sliced portion.

From the array:

import numpy as np

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

Problem: Find the sum of the middle subarray [[5, 6], [8, 9]].

Solution:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
subarr = arr[1:, 1:]
print(np.sum(subarr))  # Sum of the sliced portion

Output: 

28

 

Leave a comment

You must be logged in to post a comment.

0 Comments