Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy numpy array into part of another array

If I run the following:

import numpy as np a = np.arange(9) a = a.reshape((3,3)) 

I will get this:

a = [[0 1 2]      [3 4 5]      [6 7 8]] 

If I create a larger array like this:

b = np.zeros((5,5)) b = [[ 0.  0.  0.  0.  0.]      [ 0.  0.  0.  0.  0.]      [ 0.  0.  0.  0.  0.]      [ 0.  0.  0.  0.  0.]      [ 0.  0.  0.  0.  0.]] 

How do I efficiently copy a into b to get an array like this?

# border of 0 surrounding a to be filled in with other data later b = [[ 0.  0.  0.  0.  0.]      [ 0.  0.  1.  2.  0.]      [ 0.  3.  4.  5.  0.]      [ 0.  6.  7.  8.  0.]      [ 0.  0.  0.  0.  0.]] 

I am looking for a function built into numpy if it exists.

like image 826
rlee827 Avatar asked Nov 19 '16 07:11

rlee827


People also ask

How do I copy a NumPy array to another array?

Conclusion: to copy data from a numpy array to another use one of the built-in numpy functions numpy. array(src) or numpy. copyto(dst, src) wherever possible.

How do I copy part of an array to another array?

The Array. Copy() method in C# is used to copy section of one array to another array. Array. Copy(src, dest, length);

Does NP array make a copy?

Slicing an array does not make a copy, it just creates a new view on the existing array's data.

How do I shallow copy the data in NumPy?

The library function copy. copy() is supposed to create a shallow copy of its argument, but when applied to a NumPy array it creates a shallow copy in sense B, i.e. the new array gets its own copy of the data buffer, so changes to one array do not affect the other. x_copy = x.


1 Answers

You can specify b[1:4, 1:4] to denote the part:

>>> import numpy as np >>> a = np.arange(9) >>> a = a.reshape((3, 3)) >>> b = np.zeros((5, 5)) >>> b[1:4, 1:4] = a >>> b array([[ 0.,  0.,  0.,  0.,  0.],        [ 0.,  0.,  1.,  2.,  0.],        [ 0.,  3.,  4.,  5.,  0.],        [ 0.,  6.,  7.,  8.,  0.],        [ 0.,  0.,  0.,  0.,  0.]])  >>> b[1:4,1:4] = a + 1  # If you really meant `[1, 2, ..., 9]` >>> b array([[ 0.,  0.,  0.,  0.,  0.],        [ 0.,  1.,  2.,  3.,  0.],        [ 0.,  4.,  5.,  6.,  0.],        [ 0.,  7.,  8.,  9.,  0.],        [ 0.,  0.,  0.,  0.,  0.]]) 
like image 50
falsetru Avatar answered Sep 18 '22 12:09

falsetru