The Wayback Machine - https://web.archive.org/web/20241120201334/https://www.geeksforgeeks.org/python-slicing-multi-dimensional-arrays/
Open In App

Python slicing multi-dimensional arrays

Last Updated : 09 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python’s NumPy package makes slicing multi-dimensional arrays a valuable tool for data manipulation and analysis. It enables efficient subset data extraction and manipulation from arrays, making it a useful skill for any programmer, engineer, or data scientist.

Python Slicing Multi-Dimensional Arrays

Slicing is a method for taking out an array section frequently used for subsetting and modifying data inside arrays. In Python, Slicing gains considerably more strength when used with multi-dimensional arrays because it may be applied along several axes.

1-D Array Slicing

In a 1-D NumPy array, slicing is performed using the [start:stop: step] notation.

Python
import numpy as np

arr = np.array([0, 1, 2, 3, 4, 5])
# Slice from index 1 to 3
sliced_arr = arr[1:4]  
print(sliced_arr)  

Output:

[1 2 3]

Multi-Dimensional Array Slicing

Now, let’s move on to slicing multi-dimensional arrays. Python NumPy allows you to slice arrays along each axis independently. This means you can extract rows, columns, or specific elements from a multi-dimensional array with ease.

Python Slicing Rows and Columns

In this example, we are slicing rows and columns.

Python
# code
import numpy as np

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

# Slicing rows

# Get the first row
row_1 = matrix[0, :]  
print(row_1)  

# Slicing columns

 # Get the second column
col_2 = matrix[:, 1] 
print(col_2)  

Output

[1, 2, 3]
[2 5 8]

Python Slicing Subarrays

In this example, we are slicing subarrays from a multi-dimensional array. This is useful when we want to extract a smaller portion of the array for further analysis or manipulation.

Python
import numpy as np

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

# Slicing a subarray
# Get a 2x2 subarray
sub_matrix = matrix[0:2, 1:3]  
print(sub_matrix)

Output

[[2 3]
[5 6]]

Slicing with Step in Python

In this example, we are using the step parameter in multi-dimensional array slicing to skip elements along each axis.

Python
import numpy as np

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

# Slicing with step
 # Skip every other row and column
sliced_matrix = matrix[::2, ::2] 
print(sliced_matrix)

Output

[[ 1  3 ]
[ 9 11 ]]

Slicing using Negative Indexing in 2-D array

In this example, we are using negative indexing to slice in a 2-D array.

Python
# Create a sample 2-D array (a list of lists)
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Slicing using negative indexing to get the last row
last_row = matrix[-1]
print("Last Row:", last_row)

# Slicing using negative indexing to get the last element of the first row
last_element_first_row = matrix[0][-1]
print("Last Element of First Row:", last_element_first_row)

# Slicing using negative indexing to get the last two elements of the second row
last_two_elements_second_row = matrix[1][-2:]
print("Last Two Elements of Second Row:", last_two_elements_second_row)

Output

Last Row: [7, 8, 9]
Last Element of First Row: 3
Last Two Elements of Second Row: [5, 6]

Slicing along Multiple Axes in Python

In this example, we are slicing along multiple axes to extract specific elements from multi-dimensional arrays.

Python
import numpy as np

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

# Combining slicing along rows and columns
sub_matrix = matrix[1:3, 0:2]
print(sub_matrix)

Output

[[4 5]
[7 8]]

Slicing using Negative Indexing in 3-D array

In this example, we first create a 3-D NumPy array called array_3d. Then, we use negative indexing to slice the last row from each 2-D matrix within the 3-D array. The slicing notation [:, :, -1] means that we’re selecting all elements along the first and second dimensions (rows and columns) and the last element along the third dimension (last row in each 2-D matrix).

Python
import numpy as np

# Create a 3-D NumPy array
array_3d = np.array([
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
    [[10, 11, 12], [13, 14, 15], [16, 17, 18]],
    [[19, 20, 21], [22, 23, 24], [25, 26, 27]]
])

# Display the original array
print("Original 3-D Array:")
print(array_3d)

# Slice the last column from each 2-D matrix
sliced_array = array_3d[:, :, -1]

# Display the sliced array
print("\nSliced 3-D Array (Last Column from Each 2-D Matrix):")
print(sliced_array)

Output

Original 3-D Array:
[[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]]
[[10 11 12]
[13 14 15]
[16 17 18]]
[[19 20 21]
[22 23 24]
[25 26 27]]]
Sliced 3-D Array (Last Row from Each 2-D Matrix):
[[ 3 6 9]
[12 15 18]
[21 24 27]]


Previous Article
Next Article

Similar Reads

Indexing Multi-dimensional arrays in Python using NumPy
In this article, we will cover the Indexing of Multi-dimensional arrays in Python using NumPy. NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific computing with Python. It contains various features.Not
3 min read
Multi-dimensional lists in Python
There can be more than one additional dimension to lists in Python. Keeping in mind that a list can hold other lists, that basic principle can be applied over and over. Multi-dimensional lists are the lists within lists. Usually, a dictionary will be the better choice rather than a multi-dimensional list in Python. Accessing a multidimensional list
3 min read
Evaluate Hermite series at points x when coefficients are multi-dimensional using NumPy in Python
In this article, we will cover how to evaluate a Hermite series at points x with a multidimensional coefficient array in Python using NumPy. Example Input: [[11 12][13 14]] Output: [[37. 63.][40. 68.]] Explanation: Hermite series at points x.NumPy.polynomial.hermite.hermval method To evaluate a Hermite series at points x with a multidimensional coe
3 min read
Evaluate a Hermite_e series at points x when coefficients are multi-dimensional in Python
In this article, we will discuss how to evaluate a Hermite_e series at points x when coefficients are multi-dimensional in Python We use the hermite.hermeval() function from the numpy module. Syntax: hermite_e.hermeval(x,Arr) Parameters : x (required parameter): 'x' can be a single number or list of numbers but the only condition is the 'x' or the
2 min read
How to Concatenate two 2-dimensional NumPy Arrays?
Sometimes it might be useful or required to concatenate or merge two or more of these NumPy arrays. In this article, we will discuss various methods of concatenating two 2D arrays. But first, we have to import the NumPy package to use it: # import numpy package import numpy as np Then two 2D arrays have to be created to perform the operations, by u
5 min read
Interesting facts about strings in Python | Set 2 (Slicing)
Creating a String Strings in Python can be created using single quotes or double quotes or even triple quotes. # Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World' print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'
4 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
Python Slicing | Reverse an array in groups of given size
Given an array, reverse every sub-array formed by consecutive k elements. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] k = 3 Output: [3, 2, 1, 6, 5, 4, 9, 8, 7] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 Output: [5, 4, 3, 2, 1, 8, 7, 6] Input: arr = [1, 2, 3, 4, 5, 6] k = 1 Output: [1, 2, 3, 4, 5, 6] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k =
5 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python Slicing | Extract ‘k’ bits from a given position
How to extract ‘k’ bits from a given position ‘p’ in a number? Examples: Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is represented as 1001000 in binary, so, you should get o
4 min read
Python | Custom slicing in List
Sometimes, while working with Python, we can come to a problem in which we need to perform the list slicing. There can be many variants of list slicing. One can have custom slice interval and slicing elements. Let's discuss problem to such problem. Method : Using compress() + cycle() The combination of above functions can be used to perform this pa
2 min read
Program to cyclically rotate an array by one in Python | List Slicing
Given an array, cyclically rotate the array clockwise by one. In this article, we will see how to cyclically rotate an array by one in Python. Example Input: arr = [1, 2, 3, 4, 5]Output: arr = [5, 1, 2, 3, 4]Reference: Program to cyclically rotate an array by one Python Program to Cyclically Rotate an Array by One in PythonBelow are the methods or
2 min read
Python List Comprehension and Slicing
List comprehension is an elegant way to define and create a list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
5 min read
Slicing with Negative Numbers in Python
Slicing is an essential concept in Python, it allows programmers to access parts of sequences such as strings, lists, and tuples. In this article, we will learn how to perform slicing with negative indexing in Python. Indexing in PythonIn the world of programming, indexing starts at 0, and Python also follows 0-indexing what makes Python different
6 min read
String Slicing in Python
String slicing in Python is a way to get specific parts of a string by using start, end, and step values. It’s especially useful for text manipulation and data parsing. Let’s take a quick example of string slicing: [GFGTABS] Python s = "Hello, Python!" # Slice string from index 0 to index 5 (exclusive) s2 = s[0:5] print(s2) [/GFGTABS]Outp
4 min read
Python List Slicing
Python list slicing is fundamental concept that let us easily access specific elements in a list. In this article, we’ll learn the syntax and how to use both positive and negative indexing for slicing with examples. Example: Get the items from a list starting at position 1 and ending at position 4 (exclusive). [GFGTABS] Python a = [1, 2, 3, 4, 5, 6
5 min read
Implementing slicing in __getitem__
The __getitem__ method is used for accessing list items, array elements, dictionary entries etc. slice is a constructor in Python that creates slice object to represent set of indices that the range(start, stop, step) specifies. __getitem__ method can be implement in a class, and the behavior of slicing can be defined inside it. Syntax: __getitem__
2 min read
Data Slicing using PyQtGraph
In this article, we will see how we can perform data slicing using PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and sec
5 min read
Basic Slicing and Advanced Indexing in NumPy
Indexing a NumPy array means accessing the elements of the NumPy array at the given index. There are two types of indexing in NumPy: basic indexing and advanced indexing. Slicing a NumPy array means accessing the subset of the array. It means extracting a range of elements from the data. In this tutorial, we will cover basic slicing and advanced in
5 min read
Python - Pairwise distances of n-dimensional space array
scipy.stats.pdist(array, axis=0) function calculates the Pairwise distances between observations in n-dimensional space. Parameters : array: Input array or object having the elements to calculate the Pairwise distances axis: Axis along which to be computed. By default axis = 0 Returns : Pairwise distances of the array elements based on the set para
1 min read
Create and display a one-dimensional array-like object using Pandas in Python
Series() is a function present in the Pandas library that creates a one-dimensional array and can hold any type of objects or data in it. In this article, let us learn the syntax, create and display one-dimensional array-like object containing an array of data using Pandas library. pandas.Series() Syntax : pandas.Series(parameters) Parameters : dat
2 min read
Discrete Linear Convolution of Two One-Dimensional Sequences and Get Where they Overlap in Python
In this article, we will be looking at the approach to returning the discrete linear convolution of two one-dimensional sequences and getting where they overlap in Python. Numpy np.convolve() To return the discrete linear convolution of two one-dimensional sequences, the user needs to call the numpy.convolve() method of the Numpy library in Python.
3 min read
Three-dimensional Plotting in Python using Matplotlib
3D plots are very important tools for visualizing data that have three dimensions such as data that have two dependent and one independent variable. By plotting data in 3d plots we can get a deeper understanding of data that have three variables. We can use various matplotlib library functions to plot 3D plots. Example Of Three-dimensional Plotting
6 min read
Make a Pandas DataFrame with two-dimensional list | Python
In this discussion, we will illustrate the process of creating a Pandas DataFrame with the two-dimensional list. Python is widely recognized for its effectiveness in data analysis, thanks to its robust ecosystem of data-centric packages. Among these packages, Pandas stands out, streamlining the import and analysis of data. There are various methods
3 min read
Creating a one-dimensional NumPy array
The One-dimensional array contains elements only in one dimension. In other words, the shape of the NumPy array should contain only one value in the tuple. Let us see how to create 1-dimensional NumPy arrays. Create 1-D NumPy Array using Array() FunctionIn NumPy, you can create a 1-D array using the "array" function, which converts a Python list or
3 min read
Combining a one and a two-dimensional NumPy Array
Sometimes we need to combine 1-D and 2-D arrays and display their elements. Numpy has a function named as numpy.nditer(), which provides this facility. Syntax: numpy.nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K', casting='safe', op_axes=None, itershape=None, buffersize=0) Example 1: C/C++ Code # importing Numpy package import nump
2 min read
One-Dimensional Tensor in Pytorch
In this article, we are going to discuss a one-dimensional tensor in Python. We will look into the following concepts: Creation of One-Dimensional TensorsAccessing Elements of TensorSize of TensorData Types of Elements of TensorsView of TensorFloating Point TensorIntroduction The Pytorch is used to process the tensors. Tensors are multidimensional
5 min read
Count pairs of points having distance between them equal to integral values in a K-dimensional space
Given an array points[] representing N points in a K-dimensional space, the task is to find the count of pairs of points in the space such that the distance between the points of each pair is an integer value. Examples: Input: points[] = { {1, 2}, {5, 5}, {2, 8} }, K = 2Output: 1Explanation: Distance between points of the pair(points[0], points[1])
7 min read
How to filter two-dimensional NumPy array based on condition ?
In this article, we are going to see how to apply the filter by the given condition in NumPy two-dimensional array. We have to obtain the output of required elements i.e., whatever we want to filter the elements from the existing array or new array. Here we are going to create a two-dimensional array in numpy. C/C++ Code import numpy as np # 2-D Ar
4 min read
Two-Dimensional Tensors in Pytorch
PyTorch is a python library developed by Facebook to run and train machine learning and deep learning models. In PyTorch everything is based on tensor operations. Two-dimensional tensors are nothing but matrices or vectors of two-dimension with specific datatype, of n rows and n columns. Representation: A two-dimensional tensor has the below repres
3 min read
three90RightbarBannerImg