Replace subarrays in numpy

Given an array,

>>> n = 2
>>> a = numpy.array([[[1,1,1],[1,2,3],[1,3,4]]]*n)
>>> a
array([[[1, 1, 1],
        [1, 2, 3],
        [1, 3, 4]],

       [[1, 1, 1],
        [1, 2, 3],
        [1, 3, 4]]])

I know that it is possible to replace the values ​​in it concisely, so,

>>> a[a==2] = 0
>>> a
array([[[1, 1, 1],
        [1, 0, 3],
        [1, 3, 4]],

       [[1, 1, 1],
        [1, 0, 3],
        [1, 3, 4]]])

Is it possible to do the same for the entire row (last axis) in the array? I know that it a[a==[1,2,3]] = 11will work and replace all elements of the corresponding subarrays with 11, but I would like to replace another subarray. My intuition tells me to write the following, but the result of an error,

>>> a[a==[1,2,3]] = [11,22,33]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: array is not broadcastable to correct shape

In general, I would like to get:

array([[[1, 1, 1],
        [11, 22, 33],
        [1, 3, 4]],

       [[1, 1, 1],
        [11, 22, 33],
        [1, 3, 4]]])

... and n, of course, in the general case is much greater than 2, and the other axes are also greater than 3, so I do not want to iterate over them if I do not need it.


Update: [1,2,3](or something else I'm looking for) is not always in index 1. Example:

a = numpy.array([[[1,1,1],[1,2,3],[1,3,4]], [[1,2,3],[1,1,1],[1,3,4]]])
+5
source share
3 answers

- , , .

, .

, , , . .

data = numpy.array([[1,2,3],[55,56,57],[1,2,3]])

to_select = numpy.array([1,2,3]*3).reshape(3,3) # three rows of [1,2,3]

selected_indices = data == to_select
# array([[ True,  True,  True],
#        [False, False, False],
#        [ True,  True,  True]], dtype=bool)

data = numpy.where(selected_indices, [4,5,6], data)
# array([[4, 5, 6],
#        [55, 56, 57],
#        [4, 5, 6]])

# done in one step, but perhaps not very clear as to its intent
data = numpy.where(data == numpy.array([1,2,3]*3).reshape(3,3), [4,5,6], data)

numpy.where , , true , false.

, . - , , selected_indices, - (, 2 7). , , , selected_indices. [1,2,3], , 3x3.

+2

, np.all, , True , :

mask = np.all(a==[1,2,3], axis=2)
a[mask] = [11, 22, 23]

print(a)
#array([[[ 1,  1,  1],
#        [11, 22, 33],
#        [ 1,  3,  4]],
# 
#       [[ 1,  1,  1],
#        [11, 22, 33],
#        [ 1,  3,  4]]])
+2

Note that if this is what you want, your sample code does not create the array you are talking about. But:

>>> a = np.array([[[1,1,1],[1,2,3],[1,3,4]], [[1,1,1],[1,2,3],[1,3,4]]])
>>> a
array([[[1, 1, 1],
        [1, 2, 3],
        [1, 3, 4]],

       [[1, 1, 1],
        [1, 2, 3],
        [1, 3, 4]]])
>>> a[:,1,:] = [[8, 8, 8], [8,8,8]]
>>> a
array([[[1, 1, 1],
        [8, 8, 8],
        [1, 3, 4]],

       [[1, 1, 1],
        [8, 8, 8],
        [1, 3, 4]]])
>>> a[:,1,:] = [88, 88, 88]
>>> a
array([[[ 1,  1,  1],
        [88, 88, 88],
        [ 1,  3,  4]],

       [[ 1,  1,  1],
        [88, 88, 88],
        [ 1,  3,  4]]])
0
source

All Articles