如何用另一个数组创建或填充一个numpy数组? [英] How to create or fill an numpy array with another array?
问题描述
如何创建形状为[2, 2, 3]
的numpy数组,其中轴2处的元素是另一个数组,例如[1, 2, 3]
?
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)
产生一个类似的数组:
[[[ 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
推荐答案
有多种方法可以实现此目的.一种是在np.full
>正如Divakar在评论中指出的那样.或者,您可以使用 np.tile
为此,它允许您通过重复输入数组给定次数来构造数组.要构建示例,您可以执行以下操作:
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])
这篇关于如何用另一个数组创建或填充一个numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!