Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract part of 2D-List/Matrix/List of lists in Python

Tags:

python

list

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?

like image 500
zonksoft Avatar asked Jun 10 '12 17:06

zonksoft


People also ask

How do you get a section of a 2D array Python?

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 .

How do you access the elements of a 2D list in Python?

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.

Is a list of lists a matrix Python?

In Python, a matrix can be interpreted as a list of lists. Each element is treated as a row of the matrix.

How do you print a 2D matrix in Python?

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.


1 Answers

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]])
like image 157
weronika Avatar answered Oct 19 '22 12:10

weronika