0

I want to create an empty array and add in a for loop multiple different values. Should I use append or concatenate for this? The code is nearly working.

values=np.array([[]])
for i in range(diff.shape[0]):
  add=np.array([[i,j,k,fScore,costMST,1]])
  values=np.append([values,add])

The result should like

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

Thanks a lot

4
  • 2
    mcve could be nice Commented Aug 22, 2017 at 18:51
  • You could initialise an empty array with np.empty and just insert at that index, or you could use np.h/v/dstack. Commented Aug 22, 2017 at 18:52
  • If you're using a for loop to do anything in numpy you're doing it wrong. Commented Aug 22, 2017 at 18:53
  • You could use regular nested lists, rather than Numpy arrays too. Likely will be easier. Commented Aug 22, 2017 at 18:56

1 Answer 1

3

Use neither. np.append is just another way of calling concatenate, one that takes 2 arguments instead of a list. So both are relatively expensive, creating a new array with each call. Plus it is hard to get the initial value correct, as you have probably found.

List append is the correct way to build an array. The result will be a list or list of lists. That can be turned into an array with np.array or one of the stack (concatenate) functions at the end.

Try:

values=[]
for i in range(diff.shape[0]):
  add=np.array([[i,j,k,fScore,costMST,1]])
  values.append(add)
values = np.stack(values)

Since add is 2d, this use of stack will make a 3d. You might want vstack instead (or np.concatenate(values, axis=0) is the same thing).

Or try:

values=[]
for i in range(diff.shape[0]):
  add=[i,j,k,fScore,costMST,1]
  values.append(add)
values = np.array(values)

this makes a list of lists, which np.array turns into a 2d array.

Sign up to request clarification or add additional context in comments.

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.