0

I want to create 2D array with data from loop. Each loop iteration should add array within the array. As an example start from [ ] => [ [2,3] ] => [ [2,3] , [3,4] ] => [ [2,3] , [3,4] , [7,3] ] and likewise.

import numpy as np

output_arr = np.array([])

for i in range(0,4): 
   temp_arr = np.ones(2)
   print temp_arr.shape
   output = np.append((output_arr, temp_arr))

print output_arr.shape  

Here np.append is sample code where I need to concatenate/append/hstack arrays together... (np.append didn't work.)
How to populate 2D array within the loop?

4
  • What is your question? Commented Aug 7, 2017 at 6:27
  • How to append that it would make 2D array... np.append doesn't work... Commented Aug 7, 2017 at 6:28
  • Stick with list append that you show at the start. Then make the array from the nested list. Commented Aug 7, 2017 at 6:28
  • Forget np.append. Learn to use np.concatenate instead. Look at the np.append code to understand why I say that. Commented Aug 7, 2017 at 6:56

2 Answers 2

2

Start with an empty list:

output_arr = []

Append within the loop:

for _ in range(5):
    output_arr.append([1, 1])

Outside the loop, just call np.array:

X = np.array(output_arr)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. This works. But is there a way to do this with arrays only, not involving lists. Just asking...
@Chathuranga94 yes. If you append arrays instead of lists to the outer list, it will work. However, appending arrays to arrays is not simple, because numpy arrays are immutable. Feel free to mark accepted if it helped.
Your answer is technically what the OP asked for, but this could be done with a single list comprehension.
0

If you really just want to construct with numpy, construct an np.empty array at the beginning, and then if you need to operate on the currently filled part of the array, use output[:i+1]

import numpy as np

output_arr = np.empty((5,2))

for i in range(0,4): 
   temp_arr = np.ones(2)
   print temp_arr.shape
   output_arr[i] = temp_arr
   print output_arr[:i + 1].shape

print output_arr.shape

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.