python - Insert a numpy array into another without having to worry about length -
when doing:
import numpy = numpy.array([1,2,3,4,5,6,7,8,9,10]) b = numpy.array([1,2,3,4,5,6]) a[7:7+len(b)] = b # a[7:7+len(b)] has in fact length 3 !
we typical error:
valueerror: not broadcast input array shape (6) shape (3)
this 100% normal because a[7:7+len(b)]
has length 3, , not length = len(b)
= 6, , thus, cannot receive content of b !
how prevent happen , have content of b copied a, starting @ a[7]
:
a[7:???] = b[???] # [1 2 3 4 5 6 7 1 2 3]
this called "auto-broadcasting", i.e. don't have worry length of arrays.
edit: example if len(a) = 20
:
a = numpy.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]) b = numpy.array([1,2,3,4,5,6]) a[7:7+len(b)] = b # [ 1 2 3 4 5 6 7 1 2 3 4 5 6 14 15 16 17 18 19 20]
just tell when stop using len(a)
.
a[7:7+len(b)] = b[:len(a)-7]
example:
import numpy b = numpy.array([1,2,3,4,5,6]) = numpy.array([1,2,3,4,5,6,7,8,9,10]) a[7:7+len(b)] = b[:len(a)-7] print # [1 2 3 4 5 6 7 1 2 3] = numpy.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]) a[7:7+len(b)] = b[:len(a)-7] print # [ 1 2 3 4 5 6 7 1 2 3 4 5 6 14 15 16 17 18 19 20]
Comments
Post a Comment