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
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 .
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.
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] .
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With