简体   繁体   中英

Add Elements to array

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM