尝试使用for循环将新列追加到numpy数组中

时间:2020-06-22 22:11:41

标签: python arrays numpy loops

我正在尝试使用旧列的平均值添加新列,但是我不知道如何遍历weights数组中的列并将它们附加到class2数组中。

class1 = weights[:,sort[popsize-1]]

for x in range(1,avgmating+1):
  new = (class1 + np.array(weights[:,sort[popsize - 1 -x]]))/2
  class2 = np.hstack((class2,new))

NameError: name 'class2' is not defined

如何定义Class2,然后在每次迭代中向其添加“新”数组?

1 个答案:

答案 0 :(得分:1)

for x in range(1,avgmating+1):
  new = (class1 + np.array(weights[:,sort[popsize - 1 -x]]))/2
  if x == 1:
    class2 = new
  else:
    class2 = np.hstack((class2,new))

那行得通,但是我敢肯定有一种更快的方法...