Home > Net >  How to correctly solve this problem inside the loop?
How to correctly solve this problem inside the loop?

Time:11-10

I have an array of size (16,). How can I correctly add a sequence to it to get an array of size (16,3) inside the for loop. IMPORTANT POINT: the number of elements in array "values" can change.

import numpy as np

num_test = 16
pred = np.zeros(num_test, np.bool)

items = 3
values = np.repeat(True, 3)

print(values)

for i in range(num_test):

  # How to correctly solve this problem inside the loop?
  pred[i] = values

# For this particular case, the output should be an array of size (16,3)
print(pred)

CodePudding user response:

You can't convert (16,) to (16,3) using pred[i] = values.

You have to create array (16,3) before you try to use pred[i] = values.

pred = np.zeros((num_test, items), np.bool)

import numpy as np

num_test = 16
items = 3

pred = np.zeros((num_test, items), np.bool)  # `(16, 3)`

values = np.repeat(True, items)

#pred[:] = values

for i in range(num_test):
  pred[i] = values

print(pred.shape)
print(pred)

Eventually you can first create 3 arrays (16,) and later stack them

import numpy as np

num_test = 16
items = 3

pred1 = np.zeros(num_test, np.bool)
pred2 = np.zeros(num_test, np.bool)
pred3 = np.zeros(num_test, np.bool)

values = np.repeat(True, items)

#pred1[:] = values[0]
#pred2[:] = values[1]
#pred3[:] = values[2]

for i in range(num_test):
    pred1[i] = values[0]
    pred2[i] = values[1]
    pred3[i] = values[2]

pred = np.stack([pred1, pred2, pred3], axis=1)

print(pred.shape)
print(pred)

but it would need to use for-loop to create list with pred1, pred2, etc.


OR maybe first create normal list and later convert it ot np.array

import numpy as np

num_test = 16
items = 3

values = np.repeat(True, items)

all_values = []

for _ in range(num_test):
    all_values.append(values)

#all_values = [values for _ in range(num_test)]

pred = np.array(all_values, np.bool)

print(pred.shape)
print(pred)
  • Related