Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create or fill an numpy array with another array?

How to create an numpy array with shape [2, 2, 3], where the elements at axis 2 is another array, for example [1, 2, 3]?

So I would like to do something like this invalid code:

a = np.arange(1, 4)
b = np.full((3, 3), a)

Resulting in an array like:

[[[ 1.  2.  3.]
  [ 1.  2.  3.]]
 [[ 1.  2.  3.]
  [ 1.  2.  3.]]]

Could of course make the loop for filling like, but thought there may be a shortcut:

for y in range(b.shape[0]):
    for x in range(b.shape[1]):
        b[y, x, :] = a
like image 852
EquipDev Avatar asked Apr 21 '17 08:04

EquipDev


People also ask

How do you fill an array with another array?

You can use System. arraycopy() method. Which copies a source array from a specific beginning position to the destination array from the mentioned position. e.g. copy array a 25 times to fill in b.

How do I insert a NumPy array into another array?

You can append a NumPy array to another NumPy array by using the append() method. In this example, a NumPy array “a” is created and then another array called “b” is created. Then we used the append() method and passed the two arrays.

How do I put two arrays together in NumPy?

Joining means putting contents of two or more arrays in a single array. In SQL we join tables based on a key, whereas in NumPy we join arrays by axes. We pass a sequence of arrays that we want to join to the concatenate() function, along with the axis. If axis is not explicitly passed, it is taken as 0.

How do I fill an array in NumPy Python?

full() Function. The numpy. full() function fills an array with a specified shape and data type with a certain value. It takes the shape of the array, the value to fill, and the data type of the array as input parameters and returns an array with the specified shape and data type filled with the specified value.


2 Answers

There are multiple ways to achieve this. One is to use np.full in np.full((2,2,3), a) as pointed out by Divakar in the comments. Alternatively, you can use np.tile for this, which allows you to construct an array by repeating an input array a given number of times. To construct your example you could do:

import numpy as np

np.tile(np.arange(1, 4), [2, 2, 1])
like image 189
jotasi Avatar answered Sep 27 '22 22:09

jotasi


If your numpy version is >= 1.10 you can use broadcast_to

a = np.arange(1,4)
a.shape = (1,1,3)
b = np.broadcast_to(a,(2,2,3))

This produces a view rather than copying so will be quicker for large arrays. EDIT this looks to be the result you're asking for with your demo.

like image 35
paddyg Avatar answered Sep 27 '22 23:09

paddyg