Insert numpy array into another without worrying about length

By doing:

import numpy 
A = 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 get this typical error:

ValueError: could not broadcast input array from shape (6) into shape (3)

      

This is 100% ok, because it A[7:7+len(B)]

has length 3 and not length = len(B)

= 6 and therefore cannot receive the contents of B!

How to prevent this and easily get the content of B copied to A starting from A[7]

:

A[7:???] = B[???]     
# i would like [1 2 3 4 5 6 7 1 2 3]

      

This can be called "automatic broadcast", meaning we don't need to worry about the length of the arrays.


Edit: another 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
A # [ 1  2  3  4  5  6  7  1  2  3  4  5  6 14 15 16 17 18 19 20]

      

+3


source to share


3 answers


Just tell me when to 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])     

A = numpy.array([1,2,3,4,5,6,7,8,9,10])
A[7:7+len(B)] = B[:len(A)-7]
print A   # [1 2 3 4 5 6 7 1 2 3]

A = 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 A   # [ 1  2  3  4  5  6  7  1  2  3  4  5  6 14 15 16 17 18 19 20]

      

+1


source


import numpy 
A = numpy.array([1,2,3,4,5,6,7,8,9,10])
B = numpy.array([1,2,3,4,5,6])     

numpy.hstack((A[0:7],B))[0:len(A)]

      

the second time thought it was not so when B fits inside A. Su ....



import numpy 
A = numpy.array([1,2,3,4,5,6,7,8,9,10])
B = numpy.array([1,2,3,4,5,6])     

if 7 + len(B) > len(A):
    A = numpy.hstack((A[0:7],B))[0:len(A)]
else:
    A[7:7+len(B)] = B

      

but this kind defeats the purpose of the question! I'm sure you prefer one liner!

+1


source


Same question, but in 2d

Numpy Matrices - Overlap 2 at Specific Position

There I am trying to make it so that you better take responsibility for determining which part B

should be copied:

A[7:] = B[:3]
A[7:] = B[-3:]
A[7:] = B[3:6]

      

np.put

will do that clipping for you, but you have to give it an index list, not a slice:

np.put(x, range(7,len(x)), B)

      

which is not much better x[7:]=y[:len(x)-7]

.

The doc put

tells me that there are also functions putmask

, place

and copyto

. And the analog put

is equal take

.

Interestingly, while these other features provide more power than indexing with modes like clip and replay, I don't see them being used much. I think this is because it's easier to write a function that handles your special case rather than memorizing / searching for generic functions with many options.

0


source







All Articles