python - Replace subarrays in numpy -
given array,
>>> n = 2 >>> = numpy.array([[[1,1,1],[1,2,3],[1,3,4]]]*n) >>> array([[[1, 1, 1], [1, 2, 3], [1, 3, 4]], [[1, 1, 1], [1, 2, 3], [1, 3, 4]]]) i know it's possible replace values in succinctly so,
>>> a[a==2] = 0 >>> array([[[1, 1, 1], [1, 0, 3], [1, 3, 4]], [[1, 1, 1], [1, 0, 3], [1, 3, 4]]]) is possible same entire row (last axis) in array? know a[a==[1,2,3]] = 11 work , replace elements of matching subarrays 11, i'd substitute different subarray. intuition tells me write following, error results,
>>> a[a==[1,2,3]] = [11,22,33] traceback (most recent call last): file "<stdin>", line 1, in <module> valueerror: array not broadcastable correct shape in summary, i'd is:
array([[[1, 1, 1], [11, 22, 33], [1, 3, 4]], [[1, 1, 1], [11, 22, 33], [1, 3, 4]]]) ... , n of course is, in general, lot larger 2, , other axes larger 3, don't want loop on them if don't need to.
update: [1,2,3] (or whatever else i'm looking for) not @ index 1. example:
a = numpy.array([[[1,1,1],[1,2,3],[1,3,4]], [[1,2,3],[1,1,1],[1,3,4]]])
you have little more complicated acheive want.
you can't select slices of arrays such, can select specific indexes want.
so first need construct array represents rows wish select. ie.
data = numpy.array([[1,2,3],[55,56,57],[1,2,3]]) to_select = numpy.array([1,2,3]*3).reshape(3,3) # 3 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 1 step, perhaps not clear intent data = numpy.where(data == numpy.array([1,2,3]*3).reshape(3,3), [4,5,6], data) numpy.where works selecting second argument if true , third argument if false.
you can use select 3 different types of data. first array has same shape selected_indices, second value on own (like 2 or 7). first complicated can of shape can broadcast same shape selected_indices. in case provided [1,2,3] can stacked array shape 3x3.
Comments
Post a Comment