Adryan Ziegler
Adryan Ziegler

Reputation: 49

How to replace the first element of each array with an element from seperate list cyclically? python

For example, if i have a 3d array of size:

array_3d = np.zeros((3, 3, 3))
list1 = [1, 2, 3]

How to get the output of:

[[[1. 0. 0. 0.]
  [2. 0. 0. 0.]
  [3. 0. 0. 0.]
  [1. 0. 0. 0.]]

 [[2. 0. 0. 0.]
  [3. 0. 0. 0.]
  [1. 0. 0. 0.]
  [2. 0. 0. 0.]]

 [[3. 0. 0. 0.]
  [1. 0. 0. 0.]
  [2. 0. 0. 0.]
  [3. 0. 0. 0.]]]

I tried something like:

for i in array_3d:
   for items in zip(cycle(list1), i):
          i.append(list1)

but it didn't work

Upvotes: 0

Views: 37

Answers (3)

Kevin
Kevin

Reputation: 3368

Given that you have the following setup:

array_3d = np.zeros((3, 4, 4))
list1 = [1, 2, 3]

You could use advanced indexing to select the columns you want to modify:

array_3d[:,np.r_[:4], 0]

# array([[0., 0., 0., 0.],
#        [0., 0., 0., 0.],
#        [0., 0., 0., 0.]])

It looks like you want fill these 3 columns with list1 and wrap around out-of-bound indices:

array_3d[:,np.r_[:4], 0] = np.tile(list1, 4).reshape(3,4)

Output in array_3d:

array([[[1., 0., 0., 0.],
        [2., 0., 0., 0.],
        [3., 0., 0., 0.],
        [1., 0., 0., 0.]],

       [[2., 0., 0., 0.],
        [3., 0., 0., 0.],
        [1., 0., 0., 0.],
        [2., 0., 0., 0.]],

       [[3., 0., 0., 0.],
        [1., 0., 0., 0.],
        [2., 0., 0., 0.],
        [3., 0., 0., 0.]]])

This is the same as doing array_3d[:,:,0] = np.tile(list1, 4).reshape(3,4) (just like the answer given by Psidom)

Upvotes: 0

James Brooke
James Brooke

Reputation: 111

Seems like you are defining a 3 * 3 * 3 tensor but your desired output is 3 * 4 * 4. That aside, if you want that output in a 3 * 3 * 3:

array_3d[:, :, 0] = list1

If you want that output in a 3 * 4 * 4:

list_cycle = cycle(list1)
for i in range(array_3d.shape[0]):
    for j in range(array_3d.shape[1]):
        array_3d[i, j, 0] = next(list_cycle)

Upvotes: 2

akuiper
akuiper

Reputation: 215107

In general if array_3d.shape[1] != len(list1), you can do the following:

array_3d = np.zeros((3, 4, 4))
list1 = [1, 2, 3]

# calculate the total number elements required for a single column
fsize = array_3d.shape[0] * array_3d.shape[1]

# use tile to repeat elements in list1 so it has the same size as fsize
col = np.tile(list1, fsize // len(list1) + 1)[:fsize]
col
# [1 2 3 1 2 3 1 2 3 1 2 3]

# assign list1 to column 0
array_3d[:,:,0] = col.reshape(array_3d.shape[:2])
array_3d
#[[[1. 0. 0. 0.]
#  [2. 0. 0. 0.]
#  [3. 0. 0. 0.]
#  [1. 0. 0. 0.]]

# [[2. 0. 0. 0.]
#  [3. 0. 0. 0.]
#  [1. 0. 0. 0.]
#  [2. 0. 0. 0.]]

# [[3. 0. 0. 0.]
#  [1. 0. 0. 0.]
#  [2. 0. 0. 0.]
#  [3. 0. 0. 0.]]]

Upvotes: 2

Related Questions