Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select 'area' from a 2D array in python

Tags:

python

arrays

Is there a way to select a particular 'area' of a 2d array in python? I can use array slicing to project out only one row or column but I am unsure about how to pick a 'subarray' from the large 2d array. Thanks in advance Jack

like image 863
JMzance Avatar asked Sep 01 '14 16:09

JMzance


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 elements in a 2D array?

Accessing 2D Array Elements In Java, when accessing the element from a 2D array using arr[first][second] , the first index can be thought of as the desired row, and the second index is used for the desired column. Just like 1D arrays, 2D arrays are indexed starting at 0 .

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.

How do you select an element from a matrix in Python?

choose() With the help of Numpy matrix. choose() method, we can select the elements from a matrix by passing a parameter as an array which contain the index of row number to be selected.


1 Answers

If you are using the numpy library, you can use numpy's more advanced slicing to accomplish this like so:

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

print x[0:2,  2:4]
#       ^^^   ^^^
#       rows  cols

# Result:
[[3 4]
 [7 8]]

(more info in the numpy docs)

If you don't want to use numpy, you can use a list comprehension like this:

x = [[1, 2, 3, 4], 
     [5, 6, 7, 8], 
     [9, 10, 11, 12]]

print [row[2:4] for row in x[0:2]]
#          ^^^      ^^^ select only rows of index 0 or 1
#          ^^^ and only columns of index 2 or 3

# Result:
[[3, 4], 
 [7, 8]]
like image 162
Brionius Avatar answered Sep 21 '22 22:09

Brionius