简体   繁体   中英

numpy copying data from one array to another

I have a problem where I have a numpy 1-D array of size (622, 1) which I need to resize into an array of shape (3, 3, 3, 64) or size (1728,). So for this particular example, after copying the smaller array to bigger array, the remaining 1106 (1728 - 622) values should be zero.

NOTE: numpy array containing (622, 1) has some computed values in it.

If I use something like-

b = np.copy(a)

where 'a' is np array of size 622 and 'b' is supposed to be the np array of shape (3, 3, 3, 64). However, this np.copy() does not do what I want.

How to copy the 622 non-zero values into a larger array.

I am using Python 3.8 and numpy 1.18.

Thanks!

If you have an two arrays you can use their length to index correctly, eg:

import numpy as np

a = np.arange(622)
b = np.zeros(1728)

b[:len(a)] = a

and then you can reshape b after this.

You can create a 1D zeros array b and then assign first values of it to a , then reshape it to any shape you like:

a = np.ones((622, 1))
b = np.zeros((1728,1))
b[:a.shape[0]] = a
b = b.reshape((3,3,3,64))

output:

[[[[1. 1. 1. ... 1. 1. 1.]
   [1. 1. 1. ... 1. 1. 1.]
   [1. 1. 1. ... 1. 1. 1.]]

  [[1. 1. 1. ... 1. 1. 1.]
   [1. 1. 1. ... 1. 1. 1.]
   [1. 1. 1. ... 1. 1. 1.]]

  [[1. 1. 1. ... 1. 1. 1.]
   [1. 1. 1. ... 1. 1. 1.]
   [1. 1. 1. ... 1. 1. 1.]]]


 [[[1. 1. 1. ... 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. 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. 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.]
   [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. 0. 0. ... 0. 0. 0.]]]]

One of possible solutions:

# Create the first array (it the target code you have it)
tbl = np.arange(622).reshape(-1, 1)
# Create the second array
tbl2 = np.zeros(1106, dtype='i4').reshape(-1, 1)
# Create the result
res = np.concatenate((tbl, tbl2)).reshape(3, 3, 3, -1)

If you are not sure about the shape of res , run: res.shape and the result should be:

(3, 3, 3, 64)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM