I want to extract a part of a two-dimensional list (=list of lists) in Python. I use Mathematica a lot, and there it is very convenient to write
matrix[[2;;4,10;;13]]
which would extract the part of the matrix which is between the 2nd and 4th row as well as the 10th and 13th column.
In Python, I just used
[x[firstcolumn:lastcolumn+1] for x in matrix[firstrow:lastrow+1]]
Is there also a more elegant or efficient way to do this?
Slice Two-dimensional Numpy Arrays To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .
In Python, we can access elements of a two-dimensional array using two indices. The first index refers to the indexing of the list and the second index refers to the position of the elements. If we define only one index with an array name, it returns all the elements of 2-dimensional stored in the array.
In Python, a matrix can be interpreted as a list of lists. Each element is treated as a row of the matrix.
Output. To print out the entire two dimensional array we can use python for loop as shown below. We use end of line to print out the values in different rows.
What you want is numpy arrays and the slice operator :
.
>>> import numpy
>>> a = numpy.array([[1,2,3],[2,2,2],[5,5,5]])
>>> a
array([[1, 2, 3],
[2, 2, 2],
[5, 5, 5]])
>>> a[0:2,0:2]
array([[1, 2],
[2, 2]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With