[英]How to assign values of a 2d array to 3d array in NumPy
I'm currently working on a 3d array called X
of size (100,5,1)
. 我目前正在研究大小为
(100,5,1)
称为X
的3d数组。 I want to assign the randomly created 2d arrays called s
, dimension of (5,1)
to X
. 我想将随机创建的2d数组
s
赋给X
,其维数为(5,1)
。 My code is like below. 我的代码如下。
for i in range(100):
s = np.random.uniform(-1, 2, 5)
for j in range(5):
X[:,j,:] = s[j]
I got 100 (5,1)
arrays and they're all the same. 我有100
(5,1)
数组,它们都是一样的。 I can see why I have this result, but I can't find the solution for this. 我可以看到为什么会有这个结果,但是我找不到解决方案。
I need to have 100 unique (5,1)
arrays in X
. 我需要在
X
有100个唯一(5,1)
数组。
You are indexing the entire first dimension and thus broadcasting a single 5 x 1
array. 您正在索引整个第一维,因此广播了一个
5 x 1
数组。 This is why you are seeing copies and it only remembers the last randomly generated 5 x 1
array you've created in the loop seen over the entire first dimension. 这就是为什么看到副本的原因,它只记住在整个第一个维度上在循环中创建的最后随机生成的
5 x 1
数组。 To fix this, simply change the indexing from :
to i
. 要解决此问题,只需将索引从
:
更改为i
。
X[i,j,:] = s[j]
However, this seems like a bad code smell. 但是,这似乎是一种不好的代码气味。 I would recommend allocating the exact size you need in one go by overriding the
size
input parameter into numpy.random.uniform
. 我建议通过将
size
输入参数重写为numpy.random.uniform
,一次性分配所需的确切大小。
s = np.random.uniform(low=-1, high=2, size=(100, 5, 1))
Therefore, do not loop and just use the above statement once. 因此,不要循环,而只需使用上面的语句一次。 This makes sense as each
5 x 1
array you are creating is sampled from the same probability distribution. 这是有道理的,因为您要创建的每个
5 x 1
数组都是从相同的概率分布中采样的。 It would make more sense in an efficiency viewpoint to just allocate the desired size once. 从效率的角度来看,只分配一次所需的大小会更有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.