1
trial=[]
for i in range(100):
    trial.append(np.array([1,2,5]))
trial=np.array(trial)

The output of trial.shape is (100,3). But what I want is (3,100). I know that is not how the append works. Could you please point me to this kind of adding to a list.

Edit: Actually, I'm doing this:

firststep=[]
for i in range(bunchoffilters1.shape[0]):
          firststep.append(convolution(image,kernel=bunchoffilters1[i],non_linearity='sigmoid'))

Here, the convolution function returns 16*16 output and append gives me (30,16,16) after for loop. (bunchoffilters1.shape[0]=30). What I want is (16,16,30). Transposing might not give me correct answer as it will retain the 2nd dimension same(0,1,2)->(2,1,0) rather than getting (0,1,2)->(1,2,0)

2 Answers2

1

I'm assuming you have a process that generates a 3-element list a fixed number of times. If that's not the case, the problem is much simpler.

You have a couple of options. The simplest it to transpose the result:

trial = np.array([[1, 2, 5] for _ in range(100)]).T

A more efficeint way is to pre-allocate the buffer:

trial = np.empty((3, 100), dtype='int')
for i in range(100):
    trial[:, i] = [1, 2, 5]
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • Note that on my computer, the 2nd one is not more efficient. 66μs for the 1st, and 100μs for the second. (it is, surely, always preferable to allocate one ndarray, than appending many of them (as we see some people do from times to times ; but appending to a python list is quite efficient also) – chrslg Feb 20 '23 at 17:02
  • @chrslg. The first is just a shorthand for the full loop. In the end your bottleneck should be the process generating the values and not the bookkeeping. – Mad Physicist Feb 20 '23 at 17:53
0

What you're trying to do is to repeat the same array [1, 2, 5] 100 times along columns axis. Use numpy.repeat:

trial = np.repeat(np.array([1,2,5])[:, None], 100, axis=1)
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105