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

陌路散爱 提交于 2019-12-01 20:43:14

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

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.

Based on Divakar comment, an answer can also be:

import numpy as np
np.full([2, 2, 3], np.arange(1, 4))

Yet another possibility is:

import numpy as np
b = np.empty([2, 2, 3])
b[:] = np.arange(1, 4)

Also using np.concatenate or it's wrapper np.vstack

In [26]: a = np.arange(1,4)

In [27]: np.vstack([a[np.newaxis, :]]*4).reshape(2,2, 3)
Out[27]: 
array([[[1, 2, 3],
        [1, 2, 3]],

       [[1, 2, 3],
        [1, 2, 3]]])

In [28]: np.concatenate([a[np.newaxis, :]]*4, axis=0).reshape(2,2, 3)
Out[28]: 
array([[[1, 2, 3],
        [1, 2, 3]],

       [[1, 2, 3],
        [1, 2, 3]]])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!