Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a numpy array into another without having to worry about length

Tags:

python

numpy

When 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% normal because A[7:7+len(B)] has length 3, and not a length = len(B) = 6, and thus, cannot receive the content of B !

How to prevent this to happen and have easily the content of B copied into A, starting at A[7]:

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

This could be called "auto-broadcasting", i.e. we don't have to worry about length of 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]
like image 841
Basj Avatar asked Aug 27 '26 09:08

Basj


2 Answers

Just tell it 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]
like image 122
yashastew Avatar answered Aug 29 '26 23:08

yashastew


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

on second thought this fails the case where B fits inside A. soo....

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 sort of defeats the purpose of the question! I'm sure you prefer a one-liner!

like image 42
user1269942 Avatar answered Aug 29 '26 22:08

user1269942