Skat
Skat

Reputation: 49

Populating array elements with lists

I have following array: b=np.zeros((5,5)).astype('int32')

I wish to populate each element of above array with a list using below two arrays: x=np.linspace(11, 15, 5)

`y=np.linspace(6, 10, 5)`

The output i am looking at:

`array([[11,6], [11,7], [11,8], [11,9], [11,10]],
       [[12,6], [12,7], [12,8], [12,9], [12,10]],
       [[13,6], [13,7], [13,8], [13,9], [13,10]],
       [[14,6], [14,7], [14,8], [14,9], [14,10]],
       [[15,6], [15,7], [15,8], [15,9], [15,10]])`

Upvotes: 0

Views: 123

Answers (2)

Aleksi Torhamo
Aleksi Torhamo

Reputation: 6632

Like @DocDriven said, you'll have to adjust the shape of the b array first, to (5, 5, 2).

After that, note that you can set a whole row of y values by doing b[row,:,1] = y and a whole column of x values by doing b[:,col,0] = x.

Numpy also broadcasts shapes, which means you can use a 1d array to fill a 2d array; b[:,:,1] = y will fill all the y values in a single operation, while b[:,:,0] = x.reshape((5, 1)) will do the same for the x values.

In short, you can get what you want by doing just:

b = np.zeros((5, 5, 2)).astype('int32')
b[:,:,1] = y
b[:,:,0] = x.reshape((5, 1))

Another way is to use np.meshgrid():

b = np.array(np.meshgrid(x, y)).T.astype('int32')

Upvotes: 1

DocDriven
DocDriven

Reputation: 3974

I slightly adjusted your original numpy array because you cannot replace a single integer with a sequence.

import numpy as np

b = np.zeros((5,5,2)).astype('int32')
x = np.linspace(11, 15, 5).astype('int32')
y = np.linspace(6, 10, 5).astype('int32')

idx_x = 0
idx_y = 0

for row in b:
    for _ in row:
        b[idx_x, idx_y] = [x[idx_x], y[idx_y]]
        idx_y += 1
    idx_y = 0
    idx_x += 1

print(b.tolist())

Output:

[[[11, 6], [11, 7], [11, 8], [11, 9], [11, 10]], 
 [[12, 6], [12, 7], [12, 8], [12, 9], [12, 10]], 
 [[13, 6], [13, 7], [13, 8], [13, 9], [13, 10]], 
 [[14, 6], [14, 7], [14, 8], [14, 9], [14, 10]], 
 [[15, 6], [15, 7], [15, 8], [15, 9], [15, 10]]]

If you want to keep it as a numpy array, do not cast it via tolist().

Upvotes: 0

Related Questions