James Arten
James Arten

Reputation: 666

Filling first entries of zeros numpy array with entries of a second array

In numpy, if I have a vector of zeros like this

vec1 = np.array([0., 0., 0., 0., 0., 0., 0.])

and another one like this vec2 = np.array([1.,2.,3.]), which is the quickest way to obtain

vec3 = np.array([1., 2., 3., 0., 0., 0., 0.])

(Basicaly I want the original vector whose initial entries are filled with the ones of the second vector).

Upvotes: 0

Views: 32

Answers (1)

mozway
mozway

Reputation: 260335

It depends if you want to create a new array or modify in place.

New vec3 array (without altering vec1 and vec2):

vec3 = np.concatenate([vec2, vec1[vec2.shape[0]:]])

or

vec3 = np.r_[vec2, vec1[vec2.shape[0]:]]

Modifying vec1 in place:

vec1[:vec2.shape[0]] = vec2

used input:

vec1 = np.array([0., 0., 0., 0., 0., 0., 0.])
vec2 = np.array([1.,2.,3.])

Upvotes: 1

Related Questions