Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in numpy to use advanced list slicing and still get a view?

Tags:

python

numpy

In other words, I want to do something like

A[[-1, 0, 1], [2, 3, 4]] += np.ones((3, 3))

instead of

A[-1:3, 2:5] += np.ones((1, 3))
A[0:2, 2:5] += np.ones((2, 3))
like image 500
cheshire Avatar asked Aug 25 '10 02:08

cheshire


People also ask

Is NumPy slicing inclusive?

Slicing a One-dimensional Array Index '3' represents the starting element of the slice and it's inclusive.

Is NumPy array access faster than list?

NumPy Arrays are faster than Python Lists because of the following reasons: An array is a collection of homogeneous data-types that are stored in contiguous memory locations. On the other hand, a list in Python is a collection of heterogeneous data types stored in non-contiguous memory locations.

What does NumPy Argwhere return?

argwhere() function is used to find the indices of array elements that are non-zero, grouped by element. Parameters : arr : [array_like] Input array. Return : [ndarray] Indices of elements that are non-zero.

Why is NumPy better than lists?

There are two main reasons why we would use NumPy array instead of lists in Python. These reasons are: Less memory usage: The Python NumPy array consumes less memory than lists. Less execution time: The NumPy array is pretty fast in terms of execution, as compared to lists in Python.


1 Answers

If I understand correctly, you can do what you want to do with the following:

A[[[-1],[0],[1]],[2,3,4]] += np.ones((3, 3))

However, the numpy folks made a function, ix_, to make it a little bit easier:

A[np.ix_([-1,0,1],[2,3,4])] += np.ones((3, 3))

I hope that helps.

like image 158
Justin Peel Avatar answered Oct 25 '22 04:10

Justin Peel