• Post author:
  • Post category:NumPy / Python
  • Post last modified:March 27, 2024
  • Reading time:18 mins read
You are currently viewing NumPy Array Slicing

Python NumPy array slicing is used to extract some portion of data from the actual array. Slicing in Python means extracting data from one given index to another given index, however, NumPy slicing is slightly different. Slicing can be done with the help of (:). A NumPy array slicing object is constructed by giving start, stop, and step parameters to the built-in slicing function. This slicing object is passed to the array to extract some portion of the array.

The syntax of Python NumPy slicing is [start : stop : step]

  • Start : The starting index of the slice. This index by default considered as ‘0’
  • stop : The ending index of the slice (exclusive). This index is considered as the length of the array.
  • step : The step or stride between elements in the slice. By default, it is considered as ‘1’.

In this article, I will explain Python NumPy array slicing and how to extract some parts of data from 1-dimensional arrays, 2-dimensional arrays, and 3-dimensional arrays.

Another way to access elements from NumPy arrays is NumPy array indexing.

Note that arrays in the ndarray object follow the zero-based index.

1. Quick Examples of NumPy Array Slicing

If you are in a hurry, below are some quick examples of how to Python NumPy array slicing.


# Quick examples of numpy array slicing

# Example 1:  Extract elements 
# From index 1 to 6 (exclusive)
arr = np.array([3, 5, 7, 9, 11, 15, 18, 22])
arr2 = arr[1:6]

# Example 2: Starting position from 3 to the end
arr2 = arr[3:]

# Example 3: Elements from the beginning 
# To index 5 (exclusive)
arr2 = arr[:5]

# Example 4: Use step value to get elements
arr2 = arr[::3]

# Example 5: Use negative slicing 
# To get elements from the end
arr2 = arr[-5:-2]

# Example 6: Use slicing with interval
arr2 = arr[3::4]

# Example 7: Use slicing a 2-D arrays
arr = np.array([[3, 5, 7, 9, 11],[2, 4, 6, 8, 10]])
arr2 = arr[1:,1:3]
      
# Example 8: Use slicing a 3-D arrays
arr = np.array([[[3, 5, 7, 9, 11],
                [2, 4, 6, 8, 10]],
               [[5, 7, 8, 9, 2],
                [7, 2, 3, 6, 7]]])
arr2 = arr[0,1,0:2]

2. Slicing 1-Dimensional NumPy Arrays

Slicing 1-dimensional NumPy arrays involves extracting specific elements or subarrays from the original array. Using the slicing operation you can extract elements of a 1-D NumPy array.

You can use NumPy array slicing to create a subarray from a given array. For instance, to create a 1D array named arr with the elements [3, 5, 7, 9, 11, 15, 18, 22]. Using slicing (arr[1:6]), you extract elements from index 1 to 6 (exclusive) from the original array arr. This creates a new array named arr2. When you print arr2, you obtain the subarray [5, 7, 9, 11, 15]. This is the result of the slicing operation, where elements from index 1 to 5 of the original array are included in the subarray.


# Import numpy module
import numpy as np

# Create NumPy arrays
arr = np.array([3, 5, 7, 9, 11, 15, 18, 22])
print("Original array:",arr)

# Extract elements from index 1 to 6 (exclusive)
arr2 = arr[1:6]
print("Extract elements from index 1 to 6:",arr2) 

Yields below output.

numpy array slicing

From the above, you can observe that the result included the start index which is 5, but excluded the end index which is 18.

When you pass the elements from index 3 to the end as a parameter of the slicing operation, you will get elements of an array from index 3 to the last index.


# Create NumPy arrays
arr = np.array([3, 5, 7, 9, 11, 15, 18, 22])
print("Original array:",arr)

# Starting position from 3 to the end
arr2 = arr[3:]
print("Elements from index 3 to the end:",arr2) 

Yields below output.

numpy array slicing

In order to slicing of 1-D array pass elements from a starting index to the 5th index as a parameter of the slicing operation, you will get elements of an array from the start index to before mentioned ending index.


# Elements from the beginning to index 5 (exclusive)
arr2 = arr[:5]
print("Elements from the beginning to index 5:",arr2) 

# Output:
# Original array: [ 3  5  7  9 11 15 18 22]
# Elements from the beginning to index 5: [ 3  5  7  9 11]

Use the step value to determine the step of the slicing. It returns every other element from the entire array. Follow the syntax of slicing [start: stop: step] here, parameters are separated by a colon (:).


# Use step value to get elements
arr2 = arr[::3]
print("Extract every third element:",arr2)

# Output:
# Original array: [ 3  5  7  9 11 15 18 22]
# Extract every third element: [ 3  9 18]

In these examples, adjust the start, stop, and step parameters according to your specific requirements. Remember that NumPy slicing creates a view of the original array, so modifying the sliced array will affect the original array. If you want an independent copy, use the copy() method.

3. Use Negative Slicing To Get Elements of NumPy Array

Negative slicing in NumPy allows you to access elements from the end of the array. For example, arr[-5:-2] extracts elements starting from the fifth-to-last element up to the second-to-last element of the array

Here’s a breakdown of the slicing parameters:

  • -5: Starting from the fifth-to-last element.
  • -2: Up to the second-to-last element (exclusive).

The result is the array [11, 15, 18]. Negative slicing is a convenient way to access elements from the end of the array without explicitly knowing its length.


# Create a NumPy arrays
arr = np.array([3, 5, 7, 9, 11, 15, 18, 22])
print("Original array:",arr)

# Use negative slicing 
# To get elements from the end
arr2 = arr[-5:-2]
print("Elements using negative slicing:",arr2)

# Output:
# Original array: [ 3  5  7  9 11 15 18 22]
# Elements using negative slicing: [ 9 11 15]

From the above, you can see you have sliced elements of an array from the end.

4. Use Slicing With Interval 0f NumPy Arrays

You can use NumPy array slicing with a specified interval. For instance, arr[3::4] starts the slicing from index 3 (inclusive) and goes up to the end of the array with a step of 4. So, it includes elements at indices 3 and 7 (skipping 4, 5, 6).

  • Start slicing from index 3 (the fourth element in the array).
  • The double colons :: mean to include elements until the end of the array.
  • The 4 after the second colon indicates the step or interval between selected elements.

The result is the array [9, 15], which consists of elements from the original array with the specified interval.


# Create a NumPy arrays
arr = np.array([3, 5, 7, 9, 11, 15, 18, 22])
print("Original array:",arr)

# Use slicing with interval
arr2 = arr[3::4]
print("Slicing with interval:",arr2)

# Output:
# Original array: [ 3  5  7  9 11 15 18 22]
# Slicing with interval: [ 9 22]

5. Slicing 2-Dimensional NumPy Arrays

Slicing 2-dimensional NumPy arrays involves specifying ranges for both rows and columns. Use slicing a 2-dimensional array in both axes to obtain a rectangular subset of the original array. You can use arr[1:,1:3] to select rows 1: one to the end of the bottom of the array and columns 1:3 (columns 1 and 2).


# Create a NumPy arrays
arr = np.array([[3, 5, 7, 9, 11],[2, 4, 6, 8, 10]])
print("Original array:\n",arr)

# Use slicing a 2-D arrays
arr2 = arr[1:,1:3]
print("Slicing a 2D arrays:\n",arr2)

# Output:
# Original array:
# [[ 3  5  7  9 11]
# [ 2  4  6  8 10]]
# Slicing a 2D arrays:
# [[4 6]]

6. Slicing 3-Dimensional NumPy Arrays

To extract elements of a 3-D NumPy array using slice operation first you have to create a 3-dimensional array and then, apply slice operation.

In the below example, arr[0, 1, 0:2] extracts a subarray by selecting the element at index 0 along the first axis (matrix), the element at index 1 along the second axis (row), and the elements at indices 0 to 1 along the third axis (columns). The result is the array [2, 4].


# Slicing 3-D arrays
arr = np.array([[[3, 5, 7, 9, 11],
                 [2, 4, 6, 8, 10]],
                [[5, 7, 8, 9, 2],
                 [7, 2, 3, 6, 7]]])
      
# Use slicing a 3-D arrays
arr2 = arr[0,1,0:2]
print("Slicing a 3D arrays:\n",arr2)

# Output:
# Slicing a 3D arrays:
# [2 4]

Frequently Asked Questions On NumPy Array Slicing

What is NumPy array slicing?

NumPy array slicing is a technique in the NumPy library that allows you to extract a portion of an array to create a new array. It provides a convenient way to access and manipulate specific elements, rows, or columns within an array. Slicing is done using square brackets [] with the start, stop, and step values specified inside the brackets.

Can I slice with negative indices?

You can use negative indices for slicing in NumPy, and they have a specific meaning. Negative indices are interpreted as counting from the end of the array.

How do I slice a 2D array?

Slicing a 2D NumPy array involves specifying ranges for both rows and columns. For example, arr[0:2, 1:3] extracts the subarray consisting of rows 0 to 1 and columns 1 to 2.

How do I reverse an array using slicing?

You can reverse a NumPy array using slicing by specifying a step value of -1. For example, arr[::-1] slices the array with a step of -1, effectively reversing the order of the elements.

Can I assign values to a sliced array?

You can assign values to a sliced array in NumPy. When you assign a value to a sliced array, the values in the original array corresponding to the slice are modified.

Does slicing create a view or a copy of the array?

NumPy array slicing creates a view of the original array, not a new copy. This means that when you slice a NumPy array, you obtain a new array that refers to the same data as the original array. Any modifications made to the sliced array will affect the original array, and vice versa

Conclusion

In this article, I have explained Python NumPy array slicing techniques for extracting elements from 1-D arrays, 2-D arrays, and 3-D arrays with examples.

Happy Learning!!

References

Malli

Malli is an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly articles. Over the years, he has written hundreds of articles in Pandas, NumPy, Python, and takes pride in ability to bridge the gap between technical experts and end-users.