简体   繁体   English

将元素添加到数组

[英]Add Elements to array

I want to create an empty array and add in a for loop multiple different values. 我想创建一个空数组,并在for循环中添加多个不同的值。 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. np.append只是调用concatenate另一种方式,它需要2个参数而不是列表。 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. 可以使用np.array或最后一个stack (连接)函数将其转换为数组。

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. 由于add是2d,因此使用stack将产生3d。 You might want vstack instead (or np.concatenate(values, axis=0) is the same thing). 您可能希望使用vstack (或者np.concatenate(values, axis=0)是同一回事)。

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. 这将创建一个列表列表,其中np.array变成2d数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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