Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value to multiple slices in numpy

In Matlab, you can assign a value to multiple slices of the same list:

>> a = 1:10

a =

     1     2     3     4     5     6     7     8     9    10

>> a([1:3,7:9]) = 10

a =

    10    10    10     4     5     6    10    10    10    10

How can you do this in Python with a numpy array?

>>> a = np.arange(10)

>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> a[1:3,7:9] = 10
IndexError: too many indices
like image 848
gozzilli Avatar asked Apr 29 '13 15:04

gozzilli


People also ask

How do I take slices from an NP 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 .

What is NP R_?

numpy.r_[array[], array[]] This is used to concatenate any number of array slices along row (first) axis. This is a simple way to create numpy arrays quickly and efficiently.

How does Numpy array slicing work?

Slicing arrays Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end] . We can also define the step, like this: [start:end:step] .


1 Answers

You might also consider using np.r_:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html

ii = np.r_[0:3,7:10]
a[ii] = 10

In [11]: a
Out[11]: array([ 10, 10, 10,  3,  4,  5,  6, 10, 10,  10])
like image 190
JoshAdel Avatar answered Oct 26 '22 05:10

JoshAdel