kneazle
kneazle

Reputation: 335

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). I want to assign the randomly created 2d arrays called s, dimension of (5,1) to X. 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. 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.

Upvotes: 2

Views: 5463

Answers (1)

rayryeng
rayryeng

Reputation: 104515

You are indexing the entire first dimension and thus broadcasting a single 5 x 1 array. 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. To fix this, simply change the indexing from : to 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.

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. It would make more sense in an efficiency viewpoint to just allocate the desired size once.

Upvotes: 3

Related Questions