Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

carving 2D numpy array by index

How do i "carve" or mask a 2D numpy array according to an index formula? I don't care what the element value is, only its position in the array.

For example, given an mxm array, how do I extract all elements whose address conforms to

for i in range(0,m):
    for j in range(0,m):
        if j-i-k>=0:
            A[i,j] = 1
        elif j-p-k>=0:
            A[i,j] = 1
        elif i-k>=0:
            A[i,j] = 1
        else:
            A[i,j] = 0
        j=j+1
    i=i+1

where

k and p are an arbitrary fences

Assume

k<m
p<m

This ends up looking like a diagonal slice + a horizontal slice + a vertical slice. Can it be done without the for loops above?

like image 457
Hokiexterra Avatar asked Nov 19 '12 19:11

Hokiexterra


People also ask

How are 2D NumPy arrays indexed?

Indexing a Two-dimensional Array To access elements in this array, use two indices. One for the row and the other for the column. Note that both the column and the row indices start with 0. So if I need to access the value '10,' use the index '3' for the row and index '1' for the column.

How do I slice a NumPy 2D array?

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 .

Can you index a NumPy array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do you make a 2D NumPy array?

To create a NumPy array, you can use the function np. array() . All you need to do to create a simple array is pass a list to it. If you choose to, you can also specify the type of data in your list.


1 Answers

In [1]: import numpy as np

In [2]: k = 2

In [3]: i, j = np.ogrid[0:5,0:5]

In [4]: mask = (j-i-k < 0)

In [5]: mask
Out[5]: 
array([[ True,  True, False, False, False],
       [ True,  True,  True, False, False],
       [ True,  True,  True,  True, False],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

In [6]: mask.shape
Out[6]: (5, 5)

In [7]: mask.dtype
Out[7]: dtype('bool')
like image 110
unutbu Avatar answered Oct 10 '22 18:10

unutbu