0

i want to add rows to an empty 2d numpy array through a loop :

yi_list_for_M =np.array([])
M =[]
for x in range(6) :
    #some code 
    yi_m = np.array([y1_m,y2_m])
    yi_list_for_M = np.append(yi_list_for_M,yi_m)

the result is :

[0.         0.         2.7015625  2.5328125  4.63125    4.29375
 5.7890625  5.2828125  6.05452935 5.47381073 6.175      5.5       ]

but i want it to be :

[ [0.         0.]  ,       [2.7015625  2.5328125,] [ 4.63125    4.29375],
 [5.7890625  5.2828125 ], [6.05452935 5.47381073],[ 6.175      5.5 ]      ]

and i dont want to use lists i want to use a 1d numpy array inside a 2d numpy array

11
  • 1
    I'm having trouble understanding what you mean, but I think yi_list_for_M = np.append([yi_list_for_M,yi_m]) might be what you want? Commented Jul 11, 2021 at 17:43
  • 2
    Do not use np.append to dynamically build numpy arrays. Use a list instead. yi_list_for_M = [] and then yi_list_for_M.append(yi_m) Commented Jul 11, 2021 at 17:48
  • 1
    np.array([]) is not a 2d array! Check its shape. Commented Jul 11, 2021 at 17:54
  • 1
    You can convert the yi_list_for_M to numpy array at the end. Use numpy.append will be much slower than using list. Commented Jul 11, 2021 at 17:54
  • 2
    np.append is a poorly named frontend to np.concatenate. It makes a new array. List append operates in-place. You omitted the axis parameter, so you got a 1d array. Read the docs. Commented Jul 11, 2021 at 17:57

2 Answers 2

1

I am assuming that you will know what will be the size of each row. If yes then you can do the following:

y = np.empty((0, 3), int) #(0,n), n is the size of your row
for x in range(6):
    y.append(y, np.array([[1, 2]]), axis=0)
Sign up to request clarification or add additional context in comments.

Comments

1
yi_list_for_M = np.empty((0,2), int)
for x in range(6):
    y1_m = x**2
    y2_m = x**3
    yi_list_for_M = np.append(yi_list_for_M, np.array([[y1_m, y2_m]]), axis=0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.