Assign value to multiple slices in numpy

2019-06-15 08:35发布

问题:

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

回答1:

a = np.arange(10)
a[[range(3)+range(6,9)]] = 10
#or a[[0,1,2,6,7,8]] = 10 

print a

that should work I think ... I dont know that its quite what you want though



回答2:

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])


回答3:

From http://docs.scipy.org/doc/numpy/user/basics.indexing.html (Section "Index Arrays"). Note that indices for desired slices should be contained within 'np.array()'.

>>> x = np.arange(10,1,-1)
>>> x
array([10,  9,  8,  7,  6,  5,  4,  3,  2])

>>> x[np.array([3, 3, 1, 8])]
array([7, 7, 9, 2])